A JavaScript/TypeScript text differencing implementation. Try it out in the online demo.
Based on the algorithm proposed in "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
npm install diff --save
In an environment where you can use imports, everything you need can be imported directly from diff.
ESM:
import {diffChars, createPatch} from 'diff';
CommonJS:
const {diffChars, createPatch} = require('diff');
If you want to serve jsdiff to a web page without using a module system, you can use dist/diff.js or dist/diff.min.js. These create a global called Diff that contains the entire JsDiff API as its properties.
require('colors');
const {diffChars} = require('diff');
const one = 'beep boop';
const other = 'beep boob blah';
const diff = diffChars(one, other);
diff.forEach((part) => {
// green for additions, red for deletions
let text = part.added ? part.value.bgGreen :
part.removed ? part.value.bgRed :
part.value;
process.stderr.write(text);
});
console.log();
<pre id="display"></pre>
<script src="diff.js"></script>
<script>
const one = 'beep boop',
other = 'beep boob blah',
color = '';
let span = null;
const diff = Diff.diffChars(one, other),
display = document.getElementById('display'),
fragment = document.createDocumentFragment();
diff.forEach((part) => {
// green for additions, red for deletions
// grey for common parts
const color = part.added ? 'green' :
part.removed ? 'red' : 'grey';
span = document.createElement('span');
span.style.color = color;
span.appendChild(document
.createTextNode(part.value));
fragment.appendChild(span);
});
display.appendChild(fragment);
</script>
Diffs two blocks of text, treating each character as a token.
Options:
ignoreCase: If true, the uppercase and lowercase forms of a character are considered equal. Defaults to false.Diffs two blocks of text, treating each word and each punctuation mark as a token. Whitespace is ignored when computing the diff.
Diffs two blocks of text, treating each line as a token.
Options:
ignoreWhitespace: true to ignore leading and trailing whitespace characters. Defaults to false.stripTrailingCr: true to remove all trailing CR characters. Defaults to false.Diffs two JSON-serializable objects by first serializing them to prettily-formatted JSON and then treating each line of the JSON as a token.
Diffs two blocks of text, comparing CSS tokens.
Diffs two blocks of text, treating each sentence as a token.
Creates a unified diff patch.
Attempts to apply a unified diff patch.
Many of the methods above return change objects. These objects consist of the following fields:
value: The concatenated content of all the tokens represented by this change objectadded: true if the value was inserted into the new string, otherwise falseremoved: true if the value was removed from the old string, otherwise falsecount: How many tokens the value in the change object consists ofSee LICENSE.
daichangya