Character-by-character text comparison with Unicode support and case-insensitive options. Treats each Unicode code point as a separate token for fine-grained text analysis.
Performs character-level diff between two strings, treating each character as a token.
/**
* Compare two strings at the character level
* @param oldStr - Original string
* @param newStr - New string to compare against
* @param options - Configuration options
* @returns Array of change objects representing the diff
*/
function diffChars(oldStr, newStr, options);Options:
interface CharDiffOptions extends DiffOptions {
ignoreCase?: boolean; // Treat uppercase and lowercase as equal
}Usage Examples:
import { diffChars } from "diff";
// Basic character diff
const result = diffChars("abc", "axc");
console.log(result);
// [
// { value: "a", count: 1 },
// { value: "b", removed: true, count: 1 },
// { value: "x", added: true, count: 1 },
// { value: "c", count: 1 }
// ]
// Case-insensitive comparison
const caseResult = diffChars("Hello", "HELLO", { ignoreCase: true });
console.log(caseResult);
// [{ value: "Hello", count: 5 }] // No changes detected
// Unicode support
const unicodeResult = diffChars("café", "cafe");
// Properly handles accented characters as separate tokensVisual Diff Rendering:
import { diffChars } from "diff";
function renderDiff(oldStr, newStr) {
const diff = diffChars(oldStr, newStr);
diff.forEach((part) => {
const color = part.added ? 'green' :
part.removed ? 'red' : 'grey';
process.stderr.write(part.value[color]);
});
}
renderDiff("beep boop", "beep boob blah");Pre-configured Diff instance for character-level comparisons.
/**
* Pre-configured character diff instance
* Can be used directly or extended for custom behavior
*/
const characterDiff: Diff;Usage Examples:
import { characterDiff } from "diff";
// Direct usage
const result = characterDiff.diff("old", "new");
// Custom async usage
characterDiff.diff("old", "new", (result) => {
console.log("Async result:", result);
});For large strings, use async mode to prevent blocking:
import { diffChars } from "diff";
// Using callback for async operation
diffChars(largeOldString, largeNewString, (result) => {
console.log("Diff completed:", result);
});
// Or with options
diffChars(largeOldString, largeNewString, {
ignoreCase: true,
callback: (result) => {
console.log("Case-insensitive async diff:", result);
}
});import { diffChars } from "diff";
// Limit computation for very different strings
const result = diffChars(str1, str2, {
maxEditLength: 1000, // Stop if edit distance exceeds 1000
timeout: 5000 // Timeout after 5 seconds
});
if (!result) {
console.log("Diff computation exceeded limits");
}import { diffChars } from "diff";
// Get one change object per character
const granular = diffChars("abc", "axc", {
oneChangePerToken: true
});
// Results in separate change objects for each character
// instead of combining consecutive changes