String.prototype.localeCompare
Returns a number indicating whether the reference string comes before, after, or is equivalent to the given string in sort order
Syntax
string.localeCompare(compareString, locales?, options?)Parameters
| Parameter | Type | Description |
|---|---|---|
| compareString | string | The string to compare against |
| locales | string | string[] | A BCP 47 language tag or array of tags |
| options | Intl.CollatorOptions | Options for the comparison |
Return Value
Negative if before, positive if after, 0 if equivalent
Examples
console.log('a'.localeCompare('b')); // -1
console.log('b'.localeCompare('a')); // 1const items = ['résumé', 'cafe', 'naïve', 'über'];
items.sort((a, b) => a.localeCompare(b));
console.log(items);const a = 'ä';
console.log(a.localeCompare('z', 'de')); // negative (ä sorts before z in German)Understanding String.prototype.localeCompare
The String.prototype.localeCompare method in JavaScript returns a number indicating whether the reference string comes before, after, or is equivalent to the given string in sort order. It belongs to the String object and is one of the most widely used methods for working with string values in modern JavaScript and TypeScript applications.
The method signature is string.localeCompare(compareString, locales?, options?). It accepts 3 parameters: compareString, locales, options. When called, it returns negative if before, positive if after, 0 if equivalent. Understanding when and how to use localeCompare() helps you write more expressive, readable code.
Common use cases for String.prototype.localeCompare include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like string-normalize, array-sort, string-tolowercase, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for String.prototype.localeCompare is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
More String Methods
Other methods in the String object
Related Tools
More String Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.