Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
string-natural-compare
Advanced tools
Compare alphanumeric strings the same way a human would, using a natural order algorithm
The string-natural-compare npm package provides a way to compare strings in a human-friendly manner, often referred to as 'natural order' comparison. This is particularly useful for sorting lists of strings that include numbers, where you want the numbers to be sorted in numerical order rather than lexicographical order.
Basic Natural Comparison
This feature allows you to compare two strings in a natural order. In this example, 'file10' is compared to 'file2', and the result is 1, indicating that 'file10' comes after 'file2' in natural order.
const naturalCompare = require('string-natural-compare');
const result = naturalCompare('file10', 'file2');
console.log(result); // Output: 1
Sorting an Array
This feature allows you to sort an array of strings in natural order. In this example, the array ['file10', 'file2', 'file1'] is sorted to ['file1', 'file2', 'file10'].
const naturalCompare = require('string-natural-compare');
const files = ['file10', 'file2', 'file1'];
files.sort(naturalCompare);
console.log(files); // Output: ['file1', 'file2', 'file10']
Case-Insensitive Comparison
This feature allows you to perform a case-insensitive natural comparison. In this example, 'File10' is compared to 'file2' with case insensitivity, and the result is 1, indicating that 'File10' comes after 'file2' in natural order.
const naturalCompare = require('string-natural-compare');
const result = naturalCompare('File10', 'file2', { caseInsensitive: true });
console.log(result); // Output: 1
The natural-compare-lite package provides similar functionality for natural order string comparison but is designed to be a lighter and faster alternative. It lacks some of the additional options available in string-natural-compare, such as case insensitivity.
The alphanum-sort package offers alphanumeric sorting of arrays, which is similar to natural order comparison. It is optimized for performance and can handle large arrays efficiently. However, it does not provide as many customization options as string-natural-compare.
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.png
This 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-compare
naturalCompare(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:
['a', 'A'].sort(naturalCompareCI); // -> ['a', 'A']
['A', 'a'].sort(naturalCompareCI); // -> ['A', 'a']
// Compare strings containing large numbers
naturalCompare(
'1165874568735487968325787328996865',
'265812277985321589735871687040841'
);
// -> 1
// (Other inputs with the same ordering as this example may yield a different number > 0)
// Sorting an array of objects
const hotelRooms = [
{street: '350 5th Ave', room: 'A-1021'},
{street: '350 5th Ave', room: 'A-21046-b'}
];
// Sort by street (case-insensitive), then by room (case-sensitive)
hotelRooms.sort((a, b) => (
naturalCompare(a.street, b.street, {caseInsensitive: true}) ||
naturalCompare(a.room, b.room)
));
// When text transformation is needed or when doing a case-insensitive sort on a
// large array of objects, it is best for performance to pre-compute the
// transformed text and store it on the object. This way, the text will not need
// to be transformed for every comparison while sorting.
const cars = [
{make: 'Audi', model: 'R8'},
{make: 'Porsche', model: '911 Turbo S'}
];
// Sort by make, then by model (both case-insensitive)
for (const car of cars) {
car.sortKey = (car.make + ' ' + car.model).toLowerCase();
}
cars.sort((a, b) => naturalCompare(a.sortKey, b.sortKey));
// Using a custom alphabet (Russian alphabet)
const russianOpts = {
alphabet: 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя',
};
['Ё', 'А', 'б', 'Б'].sort((a, b) => naturalCompare(a, b, russianOpts));
// -> ['А', 'Б', 'Ё', 'б']
Note: Putting numbers in the custom alphabet can cause undefined behaviour.
FAQs
Compare alphanumeric strings the same way a human would, using a natural order algorithm
We found that string-natural-compare demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.