leven
Version:
Measure the difference between two strings using the Levenshtein distance algorithm
105 lines (60 loc) • 1.87 kB
Markdown
> Measure the difference between two strings using the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) algorithm
```sh
npm install leven
```
```js
import leven from 'leven';
leven('cat', 'cow');
//=> 2
```
Type: `string`
First string.
Type: `string`
Second string.
Type: `object`
Type: `number`
Maximum distance to calculate.
If the actual distance exceeds this value, the function will return `maxDistance` instead of the actual distance. This can significantly improve performance when you only care about matches within a certain threshold.
```js
import leven from 'leven';
leven('abcdef', '123456', {maxDistance: 3});
//=> 3
leven('cat', 'cow', {maxDistance: 5});
//=> 2
```
Find the closest matching string from an array of candidates.
Type: `string`
The string to find matches for.
Type: `string[]`
Array of candidate strings to search through.
Type: `object`
Same options as `leven()`.
Type: `number`
Maximum distance to consider. Candidates with a distance greater than this value will be ignored.
Returns the closest matching string from candidates, or `undefined` if no candidates are provided or if no match is found within `maxDistance`.
```js
import {closestMatch} from 'leven';
closestMatch('kitten', ['sitting', 'kitchen', 'mittens']);
//=> 'kitchen'
closestMatch('hello', ['jello', 'yellow', 'bellow'], {maxDistance: 2});
//=> 'jello'
// No match within distance threshold
closestMatch('abcdef', ['123456', '1234567890'], {maxDistance: 2});
//=> undefined
```
- [leven-cli](https://github.com/sindresorhus/leven-cli) - CLI for this module