difference-between-strings
Javascript

Find Diff between 2 Strings with JavaScript

Levenshtein Algorithm is a well-known method to find differences between 2 arbitrary strings. However, if the given strings have equal length, the process is very much simpler by comparing characters on the same position and record the differences.

Snippet 1

The snippet below use JavaScript split method to split the new string into an array of characters. Then iterate through the array and compare the character one by one for difference.

function findDiff(str1, str2){ 
  let diff= "";
  str2.split('').forEach(function(val, i){
    if (val != str1.charAt(i))
      diff += val ;         
  });
  return diff;
}

Usage

let diff = findDiff("test-abc-test","test-123-test");

Result

123

Live Demo – See on JSFiddle

Note
Length of both strings must be equal or the new string must be longer.

Related Libraries for Arbitrary String Diff

js-levenshtein – JS implementation calculating the Levenshtein distance

fast-diff – Implementation of O(ND) Difference Algorithm

jsdiff – JavaScript text differencing implementation. Also based on O(ND) algorithm.

Leave a Reply

Your email address will not be published. Required fields are marked *

error: