Logging differences in strings in Apps Script

It can be hard to notice where two strings are different in the Apps Script logger. We can borrow JsDiff to help with that.

I'll be using the cjsDiff library


You can report on any combination of additions, deletions or no changes. This example does them all.
  // compare
  var diffs = cjsDiff.JsDiff.diffChars(
    'quick brown fox jum ove lazy dog', 
    'the quick brown fox jumped over the lazy dog'
  Logger.log("\n" + diffs.map(function (d) {
    if (!d.removed && !d.added ) {
      return 'no changes--'+d.count + ' chars\n  '+d.value;
    if (d.removed) {
      return 'removed--' + d.count + ' chars\n  '+d.value;
    if (d.added) {
      return 'added--' + d.count + ' chars\n  '+d.value;
  }).join ("\n"));

And the result
added--4 chars
no changes--19 chars
  quick brown fox jum
added--3 chars
no changes--4 chars
added--1 chars
no changes--1 chars
added--4 chars
no changes--8 chars
  lazy dog

If that doesn't quite do it for you, There are various options you can use as documented here

For more like this, see Google Apps Scripts snippets. Why not join our forumfollow the blog or follow me on twitter to ensure you get updates when they are available. 

You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.