diff-match-patch-typescript

1.1.3 · active · verified Sun Apr 19

diff-match-patch-typescript is a direct, strongly-typed TypeScript port of Google's `diff-match-patch` library. It provides robust algorithms for computing differences between two texts, finding approximate string matches, and applying patches. This package, currently at version 1.1.3, aims for full functional parity with the original Java/JavaScript implementation, ensuring that developers leveraging TypeScript benefit from type safety and modern tooling while utilizing a widely-used and proven diffing solution. It's actively maintained with continuous integration, making it a reliable choice for text manipulation tasks where precise diffing, matching, and patching are required. Its core differentiators include its faithfulness to the original algorithm and its full TypeScript support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core functionalities: `diff_main` for comparing texts, `match_main` for finding a substring, and `patch_make`/`patch_apply` for creating and applying changes.

import { DiffMatchPatch, DiffOperation } from 'diff-match-patch-typescript';

const dmp = new DiffMatchPatch();

// Example 1: Compute a diff between two strings
const text1 = 'The quick brown fox jumps over the lazy dog.';
const text2 = 'A quick brown cat jumps over the agile fox.';
console.log('--- Diff Example ---');
const diffs = dmp.diff_main(text1, text2);
console.log('Diff result:', JSON.stringify(diffs));
// Expected output: array of [operation, text] tuples
// e.g., [[-1,"The"],[1,"A"],[0," quick brown "],[-1,"fox"],[1,"cat"],[0," jumps over the "]...]

// Example 2: Find a match within a text
const mainText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
const pattern = 'consectetur';
const startIndex = 0;
console.log('\n--- Match Example ---');
const position = dmp.match_main(mainText, pattern, startIndex);
console.log(`Pattern '${pattern}' found at position: ${position}`);
// Expected output: 28 (index of 'c' in 'consectetur')

// Example 3: Apply a patch to a text
const originalText = 'Hello World';
const newDesiredText = 'Hello TypeScript';
console.log('\n--- Patch Example ---');
const patches = dmp.patch_make(originalText, newDesiredText);
console.log('Generated patches:', JSON.stringify(patches));
const [patchedText, results] = dmp.patch_apply(patches, originalText);
console.log(`Original: '${originalText}', Patched: '${patchedText}', Success: ${results[0]}`);
// Expected output: newText: "Hello TypeScript", results: [true]

view raw JSON →