Measure the difference between two strings using the Levenshtein distance algorithm
npx @tessl/cli install tessl/npm-leven@4.0.0Leven is a highly optimized JavaScript library that calculates the Levenshtein distance between two strings. It implements several performance optimizations including prefix and suffix trimming to reduce computational workload by ignoring common prefixes and suffixes that don't contribute to the distance calculation.
npm install levenimport leven from "leven";import leven from "leven";
// Basic string comparison
leven('cat', 'cow');
//=> 2
// Identical strings return 0
leven('hello', 'hello');
//=> 0
// One empty string
leven('', 'abc');
//=> 3
// Unicode support
leven('因為我是中國人所以我會說中文', '因為我是英國人所以我會說英文');
//=> 2Leven uses an optimized implementation of the Levenshtein distance algorithm with several key performance features:
Calculates the minimum number of single-character edits (insertions, deletions, or substitutions) required to transform one string into another.
/**
* Measure the difference between two strings using the Levenshtein distance algorithm
* @param first - The first string to compare
* @param second - The second string to compare
* @returns The Levenshtein distance between the two strings
*/
function leven(first: string, second: string): number;Parameters:
first (string): The first string to comparesecond (string): The second string to compareReturns:
number: The Levenshtein distance (minimum number of single-character edits required)Performance Characteristics:
Usage Examples:
import leven from "leven";
// Simple character substitution
leven('a', 'b');
//=> 1
// Character insertions and deletions
leven('kitten', 'sitting');
//=> 3
// Complex transformations
leven('levenshtein', 'frankenstein');
//=> 6
// Edge cases
leven('', ''); // Empty strings
//=> 0
leven('abc', ''); // One empty string
//=> 3
// Unicode and international characters
leven('café', 'cafe');
//=> 1Common Use Cases: