Javascript Diff Algorithm

Javascript Diff Algorithm

Using an idea grabbed from a mailing list post, I implemented the diff algorithm discussed in the following paper (free registration required):

P. Heckel, A technique for isolating differences between files
Comm. ACM, 21, (4), 264–268 (1978).

The implementation, itself, has two functions, one of which is recommended for use:

diffString( String oldFile, String newFile )
This method takes two strings and calculates the differences in each. The final result is the ‘newFile’ marked up with HTML (to signify both deletions from the oldFile and additions to the newFile).

Sample Code

  1. document.body.innerHTML = diffString(
  2.    "The red brown fox jumped over the rolling log.",
  3.    "The brown spotted fox leaped over the rolling log"
  4. );

Sample Output

The red brown spotted fox jumped leaped over the rolling log.

Projects Using this Code:

Downloads

About the author

Written by John Resig.

If you found this post useful you may also want to check these out:

  1. PHP Operators
  2. JavaScript Tutorial Part II – Function Basics
  3. Finding the Length of a String in JavaScript
  4. Displaying Current Date with JavaScript and Basic Math Calculations
  5. Detect-and-route with JavaScript
  6. Javascript setTimeout Problem

No comments yet... Be the first to leave a reply!

Leave a Reply

You must be logged in to post a comment.