jsdiff
A javascript text differencing implementation.
A JavaScript library that compares two pieces of text and tells you exactly what changed, which parts were added, deleted, or kept, at character, word, line, or JSON level, in both Node.js and the browser.
jsdiff is a JavaScript library that compares two pieces of text and figures out exactly what changed between them. This is the same basic operation that version control tools like Git use when they show you which lines were added or removed in a file. You give the library an old version of some text and a new version, and it returns a structured description of the differences: which parts were added, which were deleted, and which stayed the same.
The library can perform this comparison at several levels of granularity. Character-level diffing looks at each individual character. Word-level diffing treats each word and punctuation mark as a unit, ignoring whitespace differences. Line-level diffing compares full lines at a time, which is how most code diff tools work. There are also modes for comparing sentences, CSS tokens, and JSON data structures. A general array-level mode lets you compare any two arrays of items, using whatever equality check makes sense for your data.
Each comparison returns a list of change objects. Every object in the list represents a span of tokens that were either inserted, deleted, or kept unchanged. You can use these objects to build your own display, generate a patch file, or apply a diff to reconstruct the modified text. The library also includes helper functions that format the output as a standard unified diff, the format used by most version control systems.
Options let you adjust the comparison behavior. For text comparisons you can turn off case sensitivity, strip trailing carriage returns when comparing files edited on different operating systems, or tell the library to treat newline characters as their own separate tokens.
jsdiff works in both Node.js and browsers. It is distributed as an npm package and can also be loaded as a standalone script file that exposes a global variable. The full README is longer than what was shown.
Where it fits
- Show a side-by-side word-level diff of two versions of a document in a browser app.
- Generate a standard unified patch file from two text strings to apply changes programmatically.
- Build a merge or review tool that highlights exactly which characters changed between two code snippets.
- Track and display live edits as a user types by diffing the previous and current value of a text field.