Compare strings containing a mix of letters and numbers in the way a human being would in sort order.
npx @tessl/cli install tessl/npm-natural-compare-lite@1.4.00
# Natural Compare Lite
1
2
Natural Compare Lite provides natural string comparison that handles mixed letters and numbers in human-readable sort order. It sorts strings the way humans expect, treating numbers within strings numerically rather than lexicographically (e.g., "img10.png" comes after "img2.png", not before).
3
4
## Package Information
5
6
- **Package Name**: natural-compare-lite
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install natural-compare-lite`
10
11
## Core Imports
12
13
CommonJS (default):
14
15
```javascript
16
const naturalCompare = require("natural-compare-lite");
17
```
18
19
ES modules (with bundler/transpiler):
20
21
```javascript
22
import naturalCompare from "natural-compare-lite";
23
```
24
25
Browser (global):
26
27
```html
28
<script src="path/to/natural-compare-lite"></script>
29
<script>
30
// Access via String.naturalCompare when CommonJS is unavailable
31
const naturalCompare = String.naturalCompare;
32
</script>
33
```
34
35
## Basic Usage
36
37
```javascript
38
const naturalCompare = require("natural-compare-lite");
39
40
// Simple array sorting
41
const files = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"];
42
files.sort(naturalCompare);
43
// Result: ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"]
44
45
// Case insensitive sorting
46
const names = ["Alice", "bob", "Charlie"];
47
names.sort((a, b) => naturalCompare(a.toLowerCase(), b.toLowerCase()));
48
49
// Object sorting by property
50
const items = [
51
{ street: "350 5th Ave", room: "A-1021" },
52
{ street: "350 5th Ave", room: "A-21046-b" }
53
];
54
items.sort((a, b) =>
55
naturalCompare(a.street, b.street) || naturalCompare(a.room, b.room)
56
);
57
```
58
59
## Capabilities
60
61
### Natural String Comparison
62
63
Compares two strings containing mixed letters and numbers in natural (human-readable) order.
64
65
```javascript { .api }
66
/**
67
* Compare two strings in natural order
68
* @param {string|any} a - First string to compare (non-strings are converted to strings)
69
* @param {string|any} b - Second string to compare (non-strings are converted to strings)
70
* @returns {number} -1 if a < b, 0 if a === b, 1 if a > b
71
*/
72
function naturalCompare(a, b);
73
```
74
75
The function handles:
76
- Numeric sequences within strings (treats "10" as larger than "2")
77
- Mixed alphanumeric content ("file2.txt" vs "file10.txt")
78
- Negative numbers ("-1" comes before "1")
79
- Decimal numbers with proper precision handling
80
- Unicode characters and custom alphabets
81
82
**Usage Examples:**
83
84
```javascript
85
// Basic comparison
86
naturalCompare("a1", "a2"); // -1 (a1 comes before a2)
87
naturalCompare("a10", "a2"); // 1 (a10 comes after a2)
88
naturalCompare("same", "same"); // 0 (strings are equal)
89
90
// Numeric sequences
91
naturalCompare("file1.txt", "file10.txt"); // -1
92
naturalCompare("version1.2", "version1.10"); // -1
93
94
// With JavaScript's sort method
95
["img1.png", "img10.png", "img2.png"].sort(naturalCompare);
96
// Result: ["img1.png", "img2.png", "img10.png"]
97
98
// Decimal numbers
99
naturalCompare("1.01", "1.001"); // 1 (maintains decimal precision)
100
naturalCompare("1.001", "1.01"); // -1
101
```
102
103
### Custom Alphabet Configuration
104
105
Configure custom character ordering for internationalization by setting the global `String.alphabet` property.
106
107
```javascript { .api }
108
/**
109
* Global alphabet configuration for custom character ordering
110
* @type {string|undefined}
111
*/
112
String.alphabet;
113
```
114
115
**Usage Examples:**
116
117
```javascript
118
// Estonian alphabet
119
String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy";
120
["t", "z", "x", "õ"].sort(naturalCompare);
121
// Result: ["z", "t", "õ", "x"] (follows Estonian ordering)
122
123
// Russian alphabet
124
String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя";
125
["Ё", "А", "Б"].sort(naturalCompare);
126
// Result: ["А", "Б", "Ё"] (follows Russian ordering)
127
128
// Reset to default behavior
129
String.alphabet = undefined;
130
```
131
132
### Browser Compatibility
133
134
In browser environments where CommonJS modules aren't available, the function is attached to `String.naturalCompare`.
135
136
```javascript { .api }
137
/**
138
* Browser-compatible reference to naturalCompare function
139
* Available when CommonJS modules are not supported
140
* @type {function}
141
*/
142
String.naturalCompare;
143
```
144
145
**Usage Example:**
146
147
```html
148
<script src="natural-compare-lite.js"></script>
149
<script>
150
// Use String.naturalCompare in browser environments
151
const files = ["file1.txt", "file10.txt", "file2.txt"];
152
files.sort(String.naturalCompare);
153
// Result: ["file1.txt", "file2.txt", "file10.txt"]
154
</script>
155
```
156
157
## Types
158
159
```javascript { .api }
160
/**
161
* Natural comparison function type
162
* @param {string} a - First string to compare
163
* @param {string} b - Second string to compare
164
* @returns {number} Comparison result: -1, 0, or 1
165
*/
166
type naturalCompare = (a: string, b: string) => number;
167
```