SkillAgentSearch skills...

Jsdiff

A javascript text differencing implementation.

Install / Use

/learn @kpdecker/Jsdiff
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

jsdiff

A JavaScript 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. e.g.

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

jsdiff's diff functions all take an old text and a new text and perform three steps:

  1. Split both texts into arrays of "tokens". What constitutes a token varies; in diffChars, each character is a token, while in diffLines, each line is a token.

  2. Find the smallest set of single-token insertions and deletions needed to transform the first array of tokens into the second.

    This step depends upon having some notion of a token from the old array being "equal" to one from the new array, and this notion of equality affects the results. Usually two tokens are equal if === considers them equal, but some of the diff functions use an alternative notion of equality or have options to configure it. For instance, by default diffChars("Foo", "FOOD") will require two deletions (o, o) and three insertions (O, O, D), but diffChars("Foo", "FOOD", {ignoreCase: true}) will require just one insertion (of a D), since ignoreCase causes o and O to be considered equal.

  3. Return an array representing the transformation computed in the previous step as a series of change objects. The array is ordered from the start of the input to the end, and each change object represents inserting one or more tokens, deleting one or more tokens, or keeping one or more tokens.

API

  • diffChars(oldStr, newStr[, options]) - diffs two blocks of text, treating each character as a token.

    ("Characters" here means Unicode code points - the elements you get when you loop over a string with a for ... of ... loop.)

    Returns a list of change objects.

    Options

    • ignoreCase: If true, the uppercase and lowercase forms of a character are considered equal. Defaults to false.
  • 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 (but preserved as far as possible in the final change objects).

    Returns a list of change objects.

    Options

    • ignoreCase: Same as in diffChars. Defaults to false.

    • intlSegmenter: An optional Intl.Segmenter object (which must have a granularity of 'word') for diffWords to use to split the text into words.

      By default, diffWords does not use an Intl.Segmenter, just some regexes for splitting text into words. This will tend to give worse results than Intl.Segmenter would, but ensures the results are consistent across environments; Intl.Segmenter behaviour is only loosely specced and the implementations in browsers could in principle change dramatically in future. If you want to use diffWords with an Intl.Segmenter but ensure it behaves the same whatever environment you run it in, use an Intl.Segmenter polyfill instead of the JavaScript engine's native Intl.Segmenter implementation.

      Using an Intl.Segmenter should allow better word-level diffing of non-English text than the default behaviour. For instance, Intl.Segmenters can generally identify via built-in dictionaries which sequences of adjacent Chinese characters form words, allowing word-level diffing of Chinese. By specifying a language when instantiating the segmenter (e.g. new Intl.Segmenter('sv', {granularity: 'word'})) you can also support language-specific rules, like treating Swedish's colon separated contractions (like k:a for kyrka) as single words; by default this would be seen as two words separated by a colon.

  • diffWordsWithSpace(oldStr, newStr[, options]) - diffs two blocks of text, treating each word, punctuation mark, newline, or run of (non-newline) whitespace as a token.

  • diffLines(oldStr, newStr[, options]) - diffs two blocks of text, treating each line as a token.

    Options

    • ignoreWhitespace: true to ignore leading and trailing whitespace characters when checking if two lines are equal. Defaults to false.
    • ignoreNewlineAtEof: true to ignore a missing newline character at the end of the last line when comparing it to other lines. (By default, the line 'b\n' in text 'a\nb\nc' is not considered equal to the line 'b' in text 'a\nb'; this option makes them be considered equal.) Ignored if ignoreWhitespace or newlineIsToken are also true.
    • stripTrailingCr: true to remove all trailing CR (\r) characters before performing the diff. Defaults to false. This helps to get a useful diff when diffing UNIX text files against Windows text files.
    • newlineIsToken: true to treat the newline character at the end of each line as its own token. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of diffLines; the default behavior with this option turned off is better suited for patches and other computer friendly output. Defaults to false.

    Note that while using ignoreWhitespace in combination with newlineIsToken is not an error, results may not be as expected. With ignoreWhitespace: true and newlineIsToken: false, changing a completely empty line to contain some spaces is treated as a non-change, but with ignoreWhitespace: true and newlineIsToken: true, it is treated as an insertion. This is because the content of a completely blank line is not a token at all in newlineIsToken mode.

    Returns a list of change objects.

  • diffSentences(oldStr, newStr[, options]) - diffs two blocks of text, treating each sentence, and the whitespace between each pair of sentences, as a token. The characters ., !, and ?, when followed by whitespace, are treated as marking the end of a sentence; nothing else besides the end of the string is considered to mark a sentence end.

    (For more sophisticated detection of sentence breaks, including support for non-English punctuation, consider instead tokenizing with an Intl.Segmenter with granularity: 'sentence' and passing the result to diffArrays.)

    Returns a list of change objects.

  • diffCss(oldStr, newStr[, options]) - diffs two blocks of text, comparing CSS tokens.

    Returns a list of change objects.

  • 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. Object properties are ordered alphabetically in the serialized JSON, so the order of properties in the objects being compared doesn't affect the result.

    Returns a list of change objects.

    Options

    • stringifyReplacer: A custom replacer function. Operates similarly to the replacer parameter to JSON.stringify(), but must be a function.
    • undefinedReplacement: A value to replace undefined with. Ignored if a stringifyReplacer is provided.
  • diffArrays(oldArr, newArr[, options]) - diffs two arrays of tokens, comparing each item for strict equality (===).

    Options

    • comparator: function(left, right) for custom equality checks

    Returns a list of change objects.

  • createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr[, oldHeader[, newHeader[, options]]]) - creates a unified diff patch by first computing a diff with diffLines and then serializing it to unified diff format.

    Parameters:

    • oldFileName: String to be output in the filename section of the patch for the removals
    • newFileName: String to be output in the filename section of the patch for the additions
    • oldStr: Original string value
    • newStr: New string value
    • oldHeader: Optional additional information to include in the old file header. Default: undefined.
    • newHeader: Optional additional information to include in the new file header. Default: undefined.
    • options: An object with options.
      • context: describes how many lines of context should be included. You can set this to Number.MAX_SAFE_INTEGER or Infinity to include the entire file content in one hunk.
      • ignoreWhitespace: Same as in diffLines. Defaults to false.
      • stripTrailingCr: Same as in diffLines. Defaults to false.
      • headerOptions: Configures the format of patch headers in the returned patch. (Note these are distinct from hunk headers, which are a mandatory part of the unified diff format and not configurable.) Has three subfields (all default to true):
        • includeIndex: whether to include a line like Index: filename.txt at the start of the patch header. (Even if this is true, this line will be omitted if oldFileName and newFileName are not identical.)
        • includeUnderline: whether to include `============================================
View on GitHub
GitHub Stars9.1k
CategoryDevelopment
Updated2d ago
Forks526

Languages

JavaScript

Security Score

95/100

Audited on Mar 24, 2026

No findings