Comparing strings lexicographically
suggest changeTo compare strings for a given locale, use localeCompare(). It returns a negative number if the reference string comes before the argument, a positive number if it comes after, and 0 if they are equal. The number is not guaranteed to be -1 or 1.
const a = "hello";
const b = "world";
console.log(a.localeCompare(b)); // a negative number
> and < also compare strings, but by UTF-16 code units, not by locale rules. "a" > "B" is true because the code unit for a is greater than the code unit for B. Those operators cannot return 0; use === for that. A code-unit version of the comparison is:
function strcmp(a, b) {
if(a === b) {
return 0;
}
if (a > b) {
return 1;
}
return -1;
}
console.log(strcmp("hello", "world")); // -1
console.log(strcmp("hello", "hello")); // 0
console.log(strcmp("world", "hello")); // 1
This is especially useful when using a sorting function that compares based on the sign of the return value (such as sort).
const arr = ["bananas", "cranberries", "apples"];
arr.sort(function(a, b) {
return a.localeCompare(b);
});
console.log(arr); // [ "apples", "bananas", "cranberries" ]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents