Finding the Difference Between Two Strings in JavaScript

Abstract image used to represent Find Differences Between Two Strings in JavaScript
Image by Kier... in Sight.

In Brief

To find the difference between two strings in JavaScript, choose the comparison method that best matches the problem. A characterbycharacter comparison is best when you need to identify the exact positions that changed. Splitting the strings into words or segments is better when you want to find changed substrings, phrases, or values rather than identify every individual character difference.

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, str2) => {
  const describe = value => value === undefined ? '[missing]' : JSON.stringify(value);
  const maxLength = Math.max(str1.length, str2.length);
  const differences = [];

  Array.from({ length: maxLength }).forEach((_, i) => {
    if (str1[i] !== str2[i]) {
      differences.push(
        `Index ${i}: ${describe(str1[i])} vs ${describe(str2[i])}`
      );
    }
  });

  return differences;
};

console.log(findCharacterDifferences('hello', 'h3llo'));
//=> ['Index 1: "e" vs "3"']

This compares each indexed position up to the longer string's length. The output uses [missing] when one string has ended and quotes actual characters, so a missing value cannot be confused with a space. JavaScript indexes UTF16 code units here; this is a positional comparison, not a full text diff.


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, str2) => {
  const diff = [];
  const str1Parts = str1.split(' ');
  const str2Parts = str2.split(' ');

  const describe = value => value === undefined ? '[missing]' : JSON.stringify(value);
  const maxLength = Math.max(str1Parts.length, str2Parts.length);

  Array.from({ length: maxLength }).forEach((_, index) => {
    const first = str1Parts[index];
    const second = str2Parts[index];

    if (first !== second) {
      diff.push(`${describe(first)} vs ${describe(second)}`);
    }
  });

  return diff;
};

console.log(
  findSubstringDifferences('I have four apples', 'I have five apples')
);
//=> ['"four" vs "five"']

Here, we split on spaces and compare corresponding positions up to the longer list of parts. A missing part is shown as [missing], whilst an empty part from an extra space is shown as "". This catches trailing words too, but an inserted word can shift every later comparison; use a proper diff algorithm when you need to align the text.


Pick the Comparison Model First

"Difference between two strings" can mean several things. You might want the first character position that changes, the substring added to one value, a full diff for highlighting, or a boolean answer for whether two values match after normalisation. Those are different problems and they deserve different code.

For short UI checks, a characterbycharacter comparison is usually fine. For editorlike behaviour, audit trails or highlighted changes, use a proper diffing approach rather than stretching a small helper beyond what it was designed to do.


Normalisation and Unicode

If the strings can contain accented characters, emoji or usergenerated content, think about Unicode normalisation before comparing. Two strings can look the same to a person but be represented differently internally. Case sensitivity, whitespace and punctuation rules should also be deliberate rather than accidental.


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.


Want to find out more?

If you need senior handson support with a complex React or Next.js platform, migration, performance issue, or technical SEO problem, send me the context and I'll tell you where I can help.