Diff in JavaScript
Several libraries make text comparison easy in JavaScript.
diff (npm)
The most popular diff library.
npm install diff
import * as Diff from 'diff';
// Character-level diff
const diff = Diff.diffChars('hello', 'hallo');
diff.forEach(part => {
const color = part.added ? 'green' : part.removed ? 'red' : 'grey';
console.log(part.value, color);
});
// Word-level diff
const wordDiff = Diff.diffWords('hello world', 'hello there');
// Line-level diff
const lineDiff = Diff.diffLines(oldText, newText);
// Create patch
const patch = Diff.createPatch('file.txt', oldText, newText);
// Apply patch
const result = Diff.applyPatch(oldText, patch);
diff2html
Render diffs as HTML.
import { html } from 'diff2html';
const diffString =
--- a/file.txt
+++ b/file.txt
@@ -1,3 +1,3 @@
line 1
-old line
+new line
line 3
;
const htmlOutput = html(diffString, {
drawFileList: true,
outputFormat: 'side-by-side'
});