package
Compare alphanumeric strings the same way a human would, using a natural order algorithm
npm install string-natural-compareGitHub-flavored package documentation.
Across all versions, last 30 days.
20,918,887 in 30 days
Runtime metadata.
Tagged topics.
Estimated unpacked size across 1 packages.
9.9 kB
Includes dependencies.
Compare alphanumeric strings the same way a human would, using a natural order algorithm (originally known as the alphanum algorithm) where numeric characters are sorted based on their numeric values rather than their ASCII values.
Standard sorting: Natural order sorting:
img1.png img1.png
img10.png img2.png
img12.png img10.png
img2.png img12.pngThis module exports a function that returns a number indicating whether one string should come before, after, or is the same as another string.
It can be used directly with the native .sort() array method.
This module can compare strings containing any size of number and is heavily tested with a custom benchmark suite to make sure that it is as fast as possible.
npm install string-natural-compare --save
# or
yarn add string-natural-comparenaturalCompare(strA, strB[, options])strA (string)strB (string)options (object) - Optional options object with the following options:
caseInsensitive (boolean) - Set to true to compare strings case-insensitively. Default: false.alphabet (string) - A string of characters that define a custom character ordering. Default: undefined.const naturalCompare = require('string-natural-compare');
// Simple, case-sensitive sorting
const files = ['z1.doc', 'z10.doc', 'z17.doc', 'z2.doc', 'z23.doc', 'z3.doc'];
files.sort(naturalCompare);
// -> ['z1.doc', 'z2.doc', 'z3.doc', 'z10.doc', 'z17.doc', 'z23.doc']
// Case-insensitive sorting
const chars = ['B', 'C', 'a', 'd'];
const naturalCompareCI = (a, b) => naturalCompare(a, b, {caseInsensitive: true});
chars.sort(naturalCompareCI);
// -> ['a', 'B', 'C', 'd']
Note: Putting numbers in the custom alphabet can cause undefined behaviour.