Intl.Collator.prototype.compare
Compares two strings according to the locale and collation options of this Intl.Collator object
Syntax
collator.compare(string1, string2)Parameters
| Parameter | Type | Description |
|---|---|---|
| string1 | string | The first string to compare |
| string2 | string | The second string to compare |
Return Value
A negative number if string1 comes before string2, positive if after, 0 if equal
Examples
const cmp = new Intl.Collator('de').compare
console.log(cmp('ä', 'z')) // negative (ä before z in German)const cmp = new Intl.Collator('en', { sensitivity: 'accent' }).compare
console.log(cmp('resume', 'résumé')) // non-zero (different accents)const collator = new Intl.Collator('en', { numeric: true })
const versions = ['v1.10', 'v1.2', 'v1.1', 'v2.0']
console.log(versions.sort(collator.compare))
// ['v1.1', 'v1.2', 'v1.10', 'v2.0']Understanding Intl.Collator.prototype.compare
The Intl.Collator.prototype.compare method in JavaScript compares two strings according to the locale and collation options of this Intl.Collator object. It belongs to the Intl.Collator object and is one of the most widely used methods for working with intl.collator values in modern JavaScript and TypeScript applications.
The method signature is collator.compare(string1, string2). It accepts 2 parameters: string1, string2. When called, it returns a negative number if string1 comes before string2, positive if after, 0 if equal. Understanding when and how to use compare() helps you write more expressive, readable code.
Common use cases for Intl.Collator.prototype.compare include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like intl-collator, string-localecompare, intl-segmenter, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Intl.Collator.prototype.compare 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
Intl.CollatorCreates an Intl.Collator object that enables language-sensitive string comparison
String.prototype.localeCompareReturns a number indicating whether the reference string comes before, after, or is equivalent to the given string in sort order
Intl.SegmenterCreates an Intl.Segmenter object that enables locale-sensitive text segmentation into graphemes, words, or sentences
Related Tools
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.