Simple diff algorithm to compare and highlight the changes in two versions of the same string.
I once wrote this diff toolset in PHP to compare edited database records. The algorithm is very simple and fast and works best with short values, e.g. from a database table with many fields. The core function compares two strings (for example two fields from two versions of an edited database record) and returns three numbers, indicating the position and length of the two substrings that are different in both strings. If only a single character was changed, this particular character is highlighted. If a line contains multiple changes, everything from the first to the last different character is highlighted.
Please note that it does not work in Internet Explorer 9 or below. Replace some []
with .charAt()
to fix this.
Old version | Current version |
---|---|
This is a simple diff algorithm. | This is a tiny diff algorithm. |
It's 140 bytes only. | It's 124 bytes only. |
It's made for database records to find the location and length of a single change per field. | It's made for database records to find the position and length of a single change per field. |
It works bets with short values since it can't separate multiple changes. | It works best with short values since it can't seperate multiple changes. |
It should not highlight lines that did not changed. | It should not highlight lines that did not changed. |
It should not fail in confusing confusing cases. | It should not fail in confusing cases. |
Show the source of this page or visit the Gist at GitHub.