Intl.Collator

Intl.Collator.prototype.compare

Compares two strings according to the locale and collation options of this Intl.Collator object

Syntax

JavaScript
collator.compare(string1, string2)

Parameters

ParameterTypeDescription
string1stringThe first string to compare
string2stringThe second string to compare

Return Value

A negative number if string1 comes before string2, positive if after, 0 if equal

Examples

Basic Usage
const cmp = new Intl.Collator('de').compare
console.log(cmp('ä', 'z')) // negative (ä before z in German)
Practical Example
const cmp = new Intl.Collator('en', { sensitivity: 'accent' }).compare
console.log(cmp('resume', 'résumé')) // non-zero (different accents)
Advanced Usage
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

Related Tools

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.