
Finding the Difference Between Two Strings in JavaScript

In our job, comparing two strings to identify their differences can be a fairly common task, especially if our application (or code within our application) is processing text or part of a wider piece of comparison logic.
There are two effective techniques I've commonly reverted back to for finding the difference between two strings, which I'd like to share with you here...
A Character‑By‑Character Comparison
By far and away, this is the simplest way to compare strings, although also a little client‑side intensive. Here, we literally step through each string, examining and comparing them character by character. This can be especially useful when you need to find out which specific characters within each string differ.
An Example in Code:
const findCharacterDifferences = (str1: string, str2: string): string[] => { const maxLength = Math.max(str1.length, str2.length); const differences: string[] = []; Array.from({ length: maxLength }).forEach((_, i) => { if (str1[i] !== str2[i]) { differences.push( `Index ${i}: '${str1[i] || ' '}' vs '${str2[i] || ' '}'` ); } }); return differences;};console.log(findCharacterDifferences('hello', 'h3llo'));//=> ["Index 1: 'e' vs '3'"]In this example, we iterate over the characters of the two strings, comparing them at each index, and then store any differences into an array. I'm deliberately safeguarding against the situation where the two strings might differ by using the maximum length of the two strings for the loop.
Finding Disjoint Substrings
It may well be that when somebody says "Find the difference between these two strings", they don't actually want you to identify every individual differing character. For a more complex comparison, you might want to identify whole substrings that are different.
This is a little more involved and requires a fairly sophisticated approach where we compare split segments of the strings.
An Example in Code:
const findSubstringDifferences = (str1: string, str2: string): string[] => { const diff: string[] = []; const str1Parts = str1.split(' '); const str2Parts = str2.split(' '); str1Parts.forEach((part, index) => { if (part !== str2Parts[index]) { diff.push(`'${part}' vs '${str2Parts[index] || ''}'`); } }); return diff;};console.log( findSubstringDifferences('I have four apples', 'I have five apples'));//=> [ "'four' vs 'five'" ]Here, we split the strings into words (I've assumed a space delimiter for the sake of simplicity ‑ your strings might be separated in a different way). Then, we compare each corresponding part using an inverse equality check, storing the strings into our result array if they differ.
Wrapping up
Aside from these two techniques (which really serve very slightly different string‑comparison cases), comparing strings in JavaScript can be achieved through a number of different methods, tailored to the specific requirements of your use case.
Categories:
Related Articles

Using Vue's Teleport for Modals and Portals. 
Simplify Asynchronous JavaScript with async/await. Simplify Asynchronous JavaScript with
async/await
Using the CSS :has Pseudo‑Class. Using the CSS
:hasPseudo‑Class
Fast and Slow Pointers: Solving the 'Linked List Cycle' Problem. Fast and Slow Pointers: Solving the 'Linked List Cycle' Problem

Introducing Seeded Randomisation into an SSR Gatsby Project. Introducing Seeded Randomisation into an SSR Gatsby Project

Browser vs. Node.js in JavaScript: Why Code Works in One and Fails in the Other. Browser vs. Node.js in JavaScript: Why Code Works in One and Fails in the Other

Optimising gatsby‑image Even Further. Optimising
gatsby‑imageEven Further
!Important in CSS. !importantin CSS
Optimising Vue.js Performance with Lazy Loading and Code Splitting. Optimising Vue.js Performance with Lazy Loading and Code Splitting

Angular Change Detection: How It Works and How to Optimise It. Angular Change Detection: How It Works and How to Optimise It

Stopping Propagation vs. Preventing Default in JavaScript. Stopping Propagation vs. Preventing Default in JavaScript

Function Declarations vs. Function Expressions vs. Arrow Functions. Function Declarations vs. Function Expressions vs. Arrow Functions