similarly
v1.0.0
Published
Compare how similar two strings are and find the best match in a list. Drop-in replacement for the deprecated string-similarity, with TypeScript types, Levenshtein, Jaro-Winkler and more. Zero dependencies.
Maintainers
Readme
similarly
Compare how similar two strings are and find the best match in a list. A drop-in replacement for the deprecated string-similarity, with TypeScript types and more algorithms.
similarly gives you a similarity score for two strings: a number from 0 to 1. 0 means they have nothing in common. 1 means they are the same. You can use it to:
- Compare two strings, for example to catch a typo in a city name.
- Find the best match for a search word in a list of strings or objects.
- Rank a list from most to least similar.
The package string-similarity (about 3 million downloads a week) is deprecated and has not had a release since 2021. similarly has the same two functions with the same results, so moving over is a one-line change.
Features
- Drop-in for string-similarity.
compareTwoStrings()andfindBestMatch()give the same numbers, the same objects and the same errors as string-similarity 4. Tested on more than 1,000 inputs against the real package. - Nine algorithms. Dice (the default), Levenshtein, Damerau-Levenshtein, Jaro, Jaro-Winkler, Jaccard, cosine, longest common subsequence and Hamming.
- Fast edit distances.
distance('kitten', 'sitting')returns3. Levenshtein compares 32 characters at a time, and amaxDistanceoption stops early, for fast "is it close?" checks. - Rank and search.
rank()andbestMatch()work on strings or objects, withthreshold,limitand akeyto pick the field. - Ignore what does not matter. Upper and lower case, accents (
caféandcafe), punctuation and spaces. - Emoji and Indian languages. Strings are split into the characters a reader sees, so
👍🏽and the Hindi syllableस्तेeach count as one character. - TypeScript types included. No other packages needed. About 4.5 KB compressed.
- Works everywhere. Node.js 20+, browsers, Deno, Bun and edge runtimes.
importandrequireboth work.
Installation
If your project uses npm:
npm install similarlyOr with another package manager:
pnpm add similarly
yarn add similarly
bun add similarlyQuick start
Get started in 3 steps
Step 1. Install the package (see Installation).
Step 2. Compare two strings.
import { similarity } from 'similarly'
similarity('Healed', 'sealed') // => 0.8
similarity('Healed', 'healed') // => 1 (case is ignored by default)Step 3. Find the best match in a list.
import { bestMatch } from 'similarly'
bestMatch('appel', ['apple', 'maple', 'banana'])
// => { item: 'apple', target: 'apple', rating: 0.5, index: 0 }That's it. Already using string-similarity? Change one line and keep your code. See Migrating from string-similarity.
Table of contents
Usage
Compare two strings
similarity() returns a score from 0 to 1. By default it uses the Dice coefficient, the same method as string-similarity: it splits each string into pairs of neighbouring characters (he, ea, al, ...) and counts how many pairs the two strings share.
import { similarity } from 'similarly'
similarity('Healed', 'sealed') // => 0.8
similarity('Asha Verma', 'Verma Asha') // => 0.8888888888888888
similarity('New Delhi', 'Mumbai') // => 0By default similarity() ignores upper and lower case. It does not ignore spaces, accents or punctuation unless you ask (see Ignore case, accents and punctuation).
If you need the exact string-similarity behaviour (case-sensitive, spaces removed), use compareTwoStrings():
import { compareTwoStrings } from 'similarly'
compareTwoStrings('healed', 'sealed') // => 0.8Find the best match
bestMatch() returns the most similar item, or undefined if the list is empty or nothing reaches the threshold.
import { bestMatch } from 'similarly'
bestMatch('appel', ['apple', 'maple', 'banana'])
// => { item: 'apple', target: 'apple', rating: 0.5, index: 0 }
bestMatch('appel', ['apple', 'maple', 'banana'], { threshold: 0.6 })
// => undefinedEach result has four fields:
item: the entry from your list.target: the text that was compared.rating: the similarity score.index: the position in your list.
When two items have the same rating, the first one wins.
Rank a list
rank() scores every item and returns them from most to least similar. Items with the same rating stay in their original order.
import { rank } from 'similarly'
rank('appel', ['apple', 'maple', 'apply', 'banana'], { limit: 2 })
// => [
// { item: 'apple', target: 'apple', rating: 0.5, index: 0 },
// { item: 'apply', target: 'apply', rating: 0.5, index: 2 },
// ]limitkeeps only the top results.thresholddrops results with a lower rating.{ threshold: 0.3 }keeps ratings of 0.3 and above.
Search objects by a field
Use key to say which text to compare. It can be a property name, or a function that returns the text. item in the result is your whole object.
import { bestMatch, rank } from 'similarly'
const people = [
{ id: 1, name: 'Asha Verma', city: 'Pune' },
{ id: 2, name: 'Ravi Menon', city: 'Kochi' },
{ id: 3, name: 'CK', city: 'Chennai' },
]
bestMatch('asha varma', people, { key: 'name' })
// => { item: { id: 1, name: 'Asha Verma', city: 'Pune' }, target: 'Asha Verma', rating: 0.7777777777777778, index: 0 }
rank('ravi kochi', people, { key: (p) => `${p.name} ${p.city}`, limit: 1 })
// => [{ item: { id: 2, ... }, target: 'Ravi Menon Kochi', rating: 0.75, index: 1 }]Items where the key gives null or undefined are skipped. Any other value that is not a string throws a TypeError.
Choose an algorithm
Pass algorithm to similarity(), rank() or bestMatch(). Every algorithm returns a score from 0 to 1.
import { similarity } from 'similarly'
similarity('MARTHA', 'MARHTA', { algorithm: 'jaroWinkler' }) // => 0.9611111111111111
similarity('kitten', 'sitting', { algorithm: 'levenshtein' }) // => 0.5714285714285714A few terms first:
- Edit distance: the number of single-character changes (insert, delete or replace) that turn one string into the other.
- Levenshtein: the most common edit distance.
kittentosittingtakes 3 changes. - n-gram: a group of
nneighbouring characters. The 2-grams (bigrams) ofnightareni,ig,ghandht. - Jaro-Winkler: counts characters that match and are close to each other, then adds a bonus when the strings start the same way. It was made for comparing names.
Which algorithm should I use?
| You want to | Use | Why |
|---|---|---|
| Replace string-similarity, or compare general text | 'dice' (default) | Fast. Word order matters little. |
| Catch typos in short words | 'levenshtein' | Counts the edits. Easy to explain. |
| Catch typos where two letters are swapped (teh, the) | 'damerauLevenshtein' | A swap counts as one edit, not two. |
| Match names of people or places | 'jaroWinkler' | Gives weight to the start of the string. |
| Compare sets of n-grams in a different way | 'jaccard' or 'cosine' | Common in search and data cleaning. |
| Compare long texts where characters may be inserted | 'lcs' | Longest common subsequence: characters in the same order, gaps allowed. |
| Compare codes of the same length (PIN, hash) | 'hamming' | Counts positions that differ. |
Word order is the biggest difference between them. Dice still sees the shared pairs when words are swapped. Levenshtein does not:
similarity('Asha Verma', 'Verma Asha') // => 0.8888888888888888
similarity('Asha Verma', 'Verma Asha', { algorithm: 'levenshtein' }) // => 0.19999999999999996Measure the edit distance
distance() returns a whole number of edits instead of a score.
import { distance } from 'similarly'
distance('kitten', 'sitting') // => 3
distance('teh', 'the') // => 2
distance('teh', 'the', { algorithm: 'damerauLevenshtein' }) // => 1
distance('karolin', 'kathrin', { algorithm: 'hamming' }) // => 3When you only care whether two strings are close, set maxDistance. The search stops as soon as the distance is bigger, and returns maxDistance + 1:
distance('color', 'colour', { maxDistance: 2 }) // => 1
distance('color', 'column', { maxDistance: 2 }) // => 3 (more than 2)Ignore case, accents and punctuation
All functions except compareTwoStrings() and findBestMatch() take these options:
import { similarity, normalize } from 'similarly'
similarity('Crème Brûlée', 'creme brulee') // => 0.45454545454545453
similarity('Crème Brûlée', 'creme brulee', { ignoreAccents: true }) // => 1
similarity("Rock 'n' Roll", 'rock n roll', { ignorePunctuation: true }) // => 1
similarity('New Delhi', 'NewDelhi', { ignoreWhitespace: true }) // => 1
// See the text that is compared:
normalize('Crème Brûlée!', { ignoreAccents: true, ignorePunctuation: true }) // => 'creme brulee'| Option | Default | What it does |
|---|---|---|
| caseSensitive | false | false ignores upper and lower case. |
| ignoreWhitespace | false | Removes spaces, tabs and line breaks. |
| ignorePunctuation | false | Removes punctuation such as . , ! ? - ' " and the Devanagari danda ।. Keeps symbols and emoji. |
| ignoreAccents | false | Removes accent marks: é becomes e. Vowel signs in Indian scripts are kept. |
| graphemes | true | Splits text into the characters a reader sees. See the next section. |
Text is also put into one standard Unicode form (NFC) first, so é typed as one character and é typed as e plus an accent are the same.
Work with emoji and Indian languages
Many characters are stored as more than one JavaScript "character" (UTF-16 code unit). An emoji with a skin tone is four. The Hindi syllable स्ते is four. Most string libraries count these pieces, and can split an emoji in half.
similarly splits text into graphemes, the characters a reader sees, using Intl.Segmenter:
import { distance, graphemes, bestMatch } from 'similarly'
graphemes('नमस्ते 👍🏽') // => ['न', 'म', 'स्ते', ' ', '👍🏽']
distance('👍', '👍🏽') // => 1 (one emoji changed)
distance('👍', '👍🏽', { graphemes: false }) // => 2 (two code units added)
distance('नमस्ते', 'नमस्कार') // => 2
distance('வணக்கம்', 'வணக்கம') // => 1
bestMatch('சென்னை', ['மதுரை', 'சென்னை', 'கோவை']).item // => 'சென்னை'Set graphemes: false to compare UTF-16 code units, like string-similarity. It is a little faster, and it gives finer scores when only a vowel sign inside one syllable changes.
API
similarity(a, b, options?)
function similarity(a: string, b: string, options?: SimilarityOptions): numberReturns a similarity score from 0 to 1. 1 means the strings are the same after the options are applied. Throws a TypeError if a or b is not a string.
| Option | Type | Default | What it does |
|---|---|---|---|
| algorithm | Algorithm | 'dice' | 'dice', 'levenshtein', 'damerauLevenshtein', 'jaro', 'jaroWinkler', 'jaccard', 'cosine', 'lcs' or 'hamming'. |
| n | number | 2 | n-gram size for 'dice', 'jaccard' and 'cosine'. |
| prefixScale | number | 0.1 | Jaro-Winkler: bonus for each shared starting character. |
| maxPrefix | number | 4 | Jaro-Winkler: how many starting characters can count. |
| boostThreshold | number | 0.7 | Jaro-Winkler: add the bonus only when the Jaro score is above this. 0 always adds it. |
| caseSensitive, ignoreWhitespace, ignorePunctuation, ignoreAccents, graphemes | boolean | see the table above | Change the text before comparing. |
How each algorithm turns into a score:
| Algorithm | Score |
|---|---|
| 'dice' | 2 × shared n-grams ÷ (n-grams in a + n-grams in b). Repeated n-grams are counted. |
| 'jaccard' | shared n-grams ÷ all n-grams (counted). |
| 'cosine' | Cosine of the two n-gram count vectors. |
| 'levenshtein', 'damerauLevenshtein' | 1 − distance ÷ length of the longer string. |
| 'jaro', 'jaroWinkler' | The standard formulas. Transpositions are rounded down, as in Winkler's reference code. |
| 'lcs' | 2 × length of the longest common subsequence ÷ (length of a + length of b). |
| 'hamming' | 1 − differing positions ÷ length. Throws a RangeError if the lengths differ. |
For the n-gram algorithms, two different strings shorter than n score 0, like string-similarity.
distance(a, b, options?)
function distance(a: string, b: string, options?: DistanceOptions): numberReturns the number of edits between two strings. Uses the same text options and defaults as similarity().
| Option | Type | Default | What it does |
|---|---|---|---|
| algorithm | DistanceAlgorithm | 'levenshtein' | 'levenshtein' (insert, delete, replace), 'damerauLevenshtein' (also swap two neighbours), 'hamming' (replace only, same length), or 'lcs' (insert and delete only). |
| maxDistance | number | Infinity | Stop counting above this. A result of maxDistance + 1 means "further than that". |
'damerauLevenshtein' is the optimal string alignment variant: no part of the string is edited twice. So distance('ca', 'abc', { algorithm: 'damerauLevenshtein' }) is 3, where the unrestricted version gives 2.
rank(query, candidates, options?)
function rank<T>(query: string, candidates: readonly T[], options?: MatchOptions<T>): Match<T>[]Scores every candidate and returns them sorted from highest to lowest rating. Ties keep their input order. Takes every similarity() option, plus:
| Option | Type | Default | What it does |
|---|---|---|---|
| key | string \| (item, index) => string \| null \| undefined | none | The text to compare for each item. Needed when items are not strings. |
| threshold | number | 0 | Drop results with a rating below this. |
| limit | number | no limit | Return at most this many results. |
bestMatch(query, candidates, options?)
function bestMatch<T>(query: string, candidates: readonly T[], options?: MatchOptions<T>): Match<T> | undefinedReturns the candidate with the highest rating (the first one on a tie), or undefined. Same options as rank().
Match
| Field | Type | What it is |
|---|---|---|
| item | T | The entry from your list. |
| target | string | The text that was compared. |
| rating | number | The similarity score from 0 to 1. |
| index | number | The position of the item in your list. |
compareTwoStrings(first, second)
function compareTwoStrings(first: string, second: string): numberThe string-similarity function, unchanged. Removes all whitespace, is case-sensitive, and compares UTF-16 code units with the Dice coefficient. Throws a TypeError for non-strings.
findBestMatch(mainString, targetStrings)
function findBestMatch(mainString: string, targetStrings: readonly string[]): BestMatchThe string-similarity function, unchanged. Returns:
| Field | Type | What it is |
|---|---|---|
| ratings | { target: string, rating: number }[] | One rating per target, in input order. |
| bestMatch | { target: string, rating: number } | The highest rating. The first one wins a tie. |
| bestMatchIndex | number | The position of bestMatch in targetStrings. |
Throws Error('Bad arguments: First argument should be a string, second should be an array of strings') when the arguments are wrong, exactly like string-similarity.
Other exports
| Export | What it does |
|---|---|
| normalize(text, options?) | Returns the text after the options are applied, so you can see what is compared. |
| graphemes(text) | Splits text into graphemes (the characters a reader sees). |
| algorithms | The list of algorithm names. |
| default | { compareTwoStrings, findBestMatch }, the same object string-similarity exports. |
Types: Algorithm, DistanceAlgorithm, SimilarityOptions, DistanceOptions, NormalizeOptions, MatchOptions, Match, KeyName, Rating and BestMatch.
Comparison
| | string-similarity | fastest-levenshtein | fuse.js | similarly | |---|---|---|---|---| | Not deprecated | No | Yes | Yes | Yes | | TypeScript types included | No | Yes | Yes | Yes | | No other packages needed | Yes | Yes | Yes | Yes | | ES module build | No | Yes | Yes | Yes | | Score from 0 to 1 for two strings | Yes | No | No | Yes | | Dice coefficient | Yes | No | No | Yes | | Levenshtein distance | No | Yes | No | Yes | | Jaro-Winkler | No | No | No | Yes | | Best match in a list | Yes | Yes | Yes | Yes | | Results sorted by score | No | No | Yes | Yes | | Search objects by a field | No | No | Yes | Yes | | Threshold and limit | No | No | Yes | Yes | | Option to ignore case | No | No | Yes | Yes | | Option to ignore accents | No | No | Yes | Yes | | Splits text into graphemes (emoji, Indian scripts) | No | No | No | Yes |
Checked against string-similarity 4.0.4, fastest-levenshtein 1.0.16 and fuse.js 7.5.0. fuse.js is a full search library: it also finds partial matches inside longer text and can weight several fields, which similarly does not do. fastest-levenshtein is faster for plain Levenshtein distance: about 2 times faster on short words in our benchmark.
Migrating from string-similarity
Change the package name. Your code stays the same.
- const stringSimilarity = require('string-similarity')
+ const stringSimilarity = require('similarly')
stringSimilarity.compareTwoStrings('healed', 'sealed')
// => 0.8
stringSimilarity.findBestMatch('healed', ['edward', 'sealed', 'theatre']).bestMatch
// => { target: 'sealed', rating: 0.8 }With import, both of these work:
import stringSimilarity from 'similarly'
import { compareTwoStrings, findBestMatch } from 'similarly'Then remove the old packages:
npm uninstall string-similarity @types/string-similarity
npm install similarlyThe type names Rating and BestMatch are the same as in @types/string-similarity.
When you are ready, you can move to the newer functions:
| string-similarity | similarly |
|---|---|
| compareTwoStrings(a, b) | similarity(a, b, { caseSensitive: true, ignoreWhitespace: true, graphemes: false }) gives the same numbers. Leave out options for case-insensitive, grapheme-aware scores. |
| findBestMatch(s, list).bestMatch | bestMatch(s, list) |
| findBestMatch(s, list).ratings | rank(s, list) (sorted, with index) |
| <script src=".../string-similarity.min.js"> | There is no global script build. Use <script type="module"> and import from https://cdn.jsdelivr.net/npm/similarly@1/dist/index.js. |
Notes and limitations
- Not a search engine.
similarlycompares whole strings. It does not find a word inside a long document, and it has no index. For large lists (more than about 100,000 items), use a search library or database. - Edit distances on long strings. Levenshtein handles 32 characters per step, so two 1,000-character strings take about 32,000 steps. Damerau-Levenshtein and
'lcs'check every pair of characters: about 1 million steps for the same strings. UsemaxDistancewhen you can, or'dice', which grows with the total length only. - Graphemes and Indian scripts. A grapheme is a whole syllable, so changing one vowel sign changes the whole grapheme. For typo search in Hindi, Tamil and other Indian scripts, try
graphemes: falseas well and keep what works better for your data. - Grapheme rules depend on the runtime.
Intl.Segmenterfollows the Unicode version of your JavaScript engine, so some Indian conjuncts may split differently in older browsers. WithoutIntl.Segmenter, a built-in approximation is used. It handles emoji, flags, accents and common conjuncts. - ignoreAccents removes marks from Latin, Greek and Cyrillic letters. Letters such as
ø,ß,æandłare not changed, because they are separate letters, not accented ones. - Case. Lowercasing uses
toLowerCase(), which does not depend on the user's locale. Turkish dotted and dotlessimay not match the way a Turkish reader expects. - Scores are not percentages of "sameness". Each algorithm measures something different, so a Dice score of 0.8 and a Jaro-Winkler score of 0.8 do not mean the same thing. Pick one algorithm and choose a
thresholdby testing with your own data.
Requirements
- Node.js 20 or newer, or any modern browser, Deno, Bun or edge runtime.
- Works with
importandrequire. - TypeScript types included. No other packages needed.
Credits
compareTwoStrings() and findBestMatch() follow string-similarity by Akash Kurdekar, version 4.0.4 (copyright 2018 Akash Kurdekar). Its package.json lists the ISC licence and its LICENSE file contains the MIT licence text. Both allow reuse with this notice. Thank you for a package that served millions of projects.
License
MIT
