← Back to Home

1diff-ts

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).

Installation

npm install diff --save

Getting Started

Imports

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.

Usage Examples

Basic Example in Node

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();

Basic Example in a Web Page

<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>

API Reference

diffChars(oldStr, newStr[, options])

Diffs two blocks of text, treating each character as a token.

Options:

diffWords(oldStr, newStr[, options])

Diffs two blocks of text, treating each word and each punctuation mark as a token. Whitespace is ignored when computing the diff.

diffLines(oldStr, newStr[, options])

Diffs two blocks of text, treating each line as a token.

Options:

diffJson(oldObj, newObj[, options])

Diffs two JSON-serializable objects by first serializing them to prettily-formatted JSON and then treating each line of the JSON as a token.

diffCss(oldStr, newStr[, options])

Diffs two blocks of text, comparing CSS tokens.

diffSentences(oldStr, newStr[, options])

Diffs two blocks of text, treating each sentence as a token.

createPatch(fileName, oldStr, newStr[, oldHeader[, newHeader[, options]]])

Creates a unified diff patch.

applyPatch(source, patch[, options])

Attempts to apply a unified diff patch.

Change Objects

Many of the methods above return change objects. These objects consist of the following fields:

Resources

License

See LICENSE.

Author

daichangya