Skip to content

Instantly share code, notes, and snippets.

@dustMason
Created April 15, 2011 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustMason/921264 to your computer and use it in GitHub Desktop.
Save dustMason/921264 to your computer and use it in GitHub Desktop.
Implementing one of the suggestions from http://code.google.com/p/google-diff-match-patch/wiki/Plaintext
var dmp = new diff_match_patch();
var text1 = "your input text source";
var text2 = "your input text destination";
var current_unicode = parseInt('2000',16);
var charmap = {};
var replaceFirstTag = function(str,code) {
var nu = code+1;
while (charmap.hasOwnProperty(String.fromCharCode(code.toString(16)))) code++;
var char = String.fromCharCode(code.toString(16));
var sp = str.search(/</);
var ep = str.search(/>/);
var tag = str.slice(sp,ep+1);
return [str.replace(/<.*?>/,char),char,tag];
}
while (text1.regexIndexOf(/<.*?>/,0) > 0) {
var replaced = replaceFirstTag(text1,current_unicode);
text1 = replaced[0];
text2 = text2.replace(replaced[2],replaced[1]); // also make the same substitution in the second text!
charmap[replaced[1]] = replaced[2];
current_unicode++;
}
while (text2.regexIndexOf(/<.*?>/,0) > 0) {
var replaced = replaceFirstTag(text2,current_unicode);
text2 = replaced[0];
charmap[replaced[1]] = replaced[2];
current_unicode++;
}
var d = dmp.diff_lineMode_(text1, text2);
dmp.diff_cleanupSemantic(d);
var rendered = dmp.diff_prettyHtml(d);
for (char in charmap) {
var re = new RegExp(char,"g");
rendered = rendered.replace(re,charmap[char]);
}
// rendered is the final product
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment