Finding the Difference Between Two Strings in JavaScript

Hero image for Finding the Difference Between Two Strings in JavaScript. Image by Kier... in Sight.
Hero image for 'Finding the Difference Between Two Strings in JavaScript.' Image by Kier... in Sight.

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 clientside 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 stringcomparison cases), comparing strings in JavaScript can be achieved through a number of different methods, tailored to the specific requirements of your use case.


Categories:

  1. ES6
  2. Front‑End Development
  3. JavaScript