JSDiff

by Toby Ho on 4/9/2014

JSDiff is an implementing of text comparison in Javascript, it is used in Mocha to implement colored diffs, and it's fairly easy to use.

Let's say you have two strings: oldString and newString

var oldString = 'beep boop';
var newString = 'beep boob blah';

To compare them you may use the diffChars method

var diff = JsDiff.diffChars(oldString, newString);

This gives you diff which is an array of change objects. A change object represents a section of text which is has either been added, removed, or neither. It has the following properties

In the above example, if you'd log the diff object, you'd see

[ { value: 'beep boo', added: undefined, removed: undefined },
  { value: 'b blah', added: true, removed: undefined },
  { value: 'p', added: undefined, removed: true } ]

To render this information visually, we can color code these text chunks. In Node, there's a module colors which makes outputing colors to the terminal easy.

diff.forEach(function(part){
  // green for additions, red for deletions
  // grey for common parts
  var color = part.added ? 'green' :
    part.removed ? 'red' : 'grey';
  process.stderr.write(part.value[color]);
});

If you run this program (see full source code) you should see

You can also use JSDiff on a web page by using browserify or just via <script> tag. To render the same diff using DOM elements - using the raw DOM API would look like

var display = document.createElement('pre');
diff.forEach(function(part){
  // green for additions, red for deletions
  // grey for common parts
  var color = part.added ? 'green' :
    part.removed ? 'red' : 'grey';
  var span = document.createElement('span');
  span.style.color = color;
  span.appendChild(document
    .createTextNode(part.value));
  display.appendChild(span);
});
document.body.appendChild(display);

The result of that code (full source, or on requirebin) would look like

But wait, there's more. Take a look at JsDiff's API, it can also

This article was originally posted at http://tobyho.com/2013/11/05/jsdiff-for-comparing-text/.

comments powered by Disqus