localeCompare() method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

The new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation-dependent.

句法

referenceStr.localeCompare(compareString[, locales[, options]])
					

参数

compareString
The string against which the referenceStr is compared.
locales and options

These arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used. In implementations which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent.

Intl.Collator() 构造函数 for details on these parameters and how to use them.

返回值

A negative number if referenceStr occurs before compareString ; positive referenceStr occurs after compareString ; 0 if they are equivalent.

描述

Returns an integer indicating whether the referenceStr comes before, after or is equivalent to the compareString .

  • Negative when the referenceStr occurs before compareString
  • Positive when the referenceStr occurs after compareString
  • 返回 0 if they are equivalent

Do NOT rely on exact return values of -1 or 1 !

Negative and positive integer results vary between browsers (as well as between browser versions) because the W3C specification only mandates negative and positive values. Some browsers may return -2 or 2 , or even some other negative or positive value.

Performance

When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare 特性。

范例

使用 localeCompare()

// The letter "a" is before "c" yielding a negative value
'a'.localeCompare('c'); // -2 or -1 (or some other negative value)
// Alphabetically the word "check" comes after "against" yielding a positive value
'check'.localeCompare('against'); // 2 or 1 (or some other positive value)
// "a" and "a" are equivalent yielding a neutral value of zero
'a'.localeCompare('a'); // 0
					

Sort an array

localeCompare() enables case-insensitive sorting for an array.

let items = ['réservé', 'Premier', 'Cliché', 'communiqué', 'café', 'Adieu'];
items.sort( (a, b) => a.localeCompare(b, 'fr', {ignorePunctuation: true}));
// ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']
					

Check browser support for extended arguments

locales and options arguments are not supported in all browsers yet.

To check whether an implementation supports them, use the "i" argument (a requirement that illegal language tags are rejected) and look for a RangeError exception:

function localeCompareSupportsLocales() {
  try {
    'foo'.localeCompare('bar', 'i');
  } catch (e) {
    return e.name === 'RangeError';
  }
  return false;
}
					

使用 locales

The results provided by localeCompare() vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

console.log('ä'.localeCompare('z', 'de')); // a negative value: in German, ä sorts before z
console.log('ä'.localeCompare('z', 'sv')); // a positive value: in Swedish, ä sorts after z
					

使用 options

The results provided by localeCompare() can be customized using the options argument:

// in German, ä has a as the base letter
console.log('ä'.localeCompare('a', 'de', { sensitivity: 'base' })); // 0
// in Swedish, ä and a are separate base letters
console.log('ä'.localeCompare('a', 'sv', { sensitivity: 'base' })); // a positive value
					

Numeric sorting

// by default, "2" > "10"
console.log("2".localeCompare("10")); // 1
// numeric using options:
console.log("2".localeCompare("10", undefined, {numeric: true})); // -1
// numeric using locales tag:
console.log("2".localeCompare("10", "en-u-kn-true")); // -1
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'String.prototype.localeCompare' in that specification.
ECMAScript 国际化 API (ECMA-402)
The definition of 'String.prototype.localeCompare' in that specification.

浏览器兼容性

更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
localeCompare Chrome 1 Edge 12 Firefox 1 IE 5.5 Opera 7 Safari 3 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs 0.1.100
locales Chrome 24 Edge 12 Firefox 29 IE 11 Opera 15 Safari 10 WebView Android No Chrome Android 26 Firefox Android No Opera Android No Safari iOS 10 Samsung Internet Android 1.5 nodejs 13.0.0
13.0.0
部分支持 0.12
Before version 13.0.0, only the locale data for en-US is available by default. When other locales are specified, the function silently falls back to en-US . To make full ICU (locale) data available for versions prior to 13, see Node.js documentation on the --with-intl option and how to provide the data.
options Chrome 24 Edge 12 Firefox 29 IE 11 Opera 15 Safari 10 WebView Android No Chrome Android 26 Firefox Android No Opera Android No Safari iOS 10 Samsung Internet Android 1.5 nodejs 0.12

图例

完整支持

完整支持

不支持

不支持

见实现注意事项。

另请参阅

元数据

  • 最后修改:
  1. 标准内置对象
  2. String
  3. 特性
    1. String 长度
  4. 方法
    1. String.fromCharCode()
    2. String.fromCodePoint()
    3. String.prototype.anchor()
    4. String.prototype.big()
    5. String.prototype.blink()
    6. String.prototype.bold()
    7. String.prototype.charAt()
    8. String.prototype.charCodeAt()
    9. String.prototype.codePointAt()
    10. String.prototype.concat()
    11. String.prototype.endsWith()
    12. String.prototype.fixed()
    13. String.prototype.fontcolor()
    14. String.prototype.fontsize()
    15. String.prototype.includes()
    16. String.prototype.indexOf()
    17. String.prototype.italics()
    18. String.prototype.lastIndexOf()
    19. String.prototype.link()
    20. String.prototype.localeCompare()
    21. String.prototype.match()
    22. String.prototype.matchAll()
    23. String.prototype.normalize()
    24. String.prototype.padEnd()
    25. String.prototype.padStart()
    26. String.prototype.repeat()
    27. String.prototype.replace()
    28. String.prototype.replaceAll()
    29. String.prototype.search()
    30. String.prototype.slice()
    31. String.prototype.small()
    32. String.prototype.split()
    33. String.prototype.startsWith()
    34. String.prototype.strike()
    35. String.prototype.sub()
    36. String.prototype.substr()
    37. String.prototype.substring()
    38. String.prototype.sup()
    39. String.prototype.toLocaleLowerCase()
    40. String.prototype.toLocaleUpperCase()
    41. String.prototype.toLowerCase()
    42. String.prototype.toSource()
    43. String.prototype.toString()
    44. String.prototype.toUpperCase()
    45. String.prototype.trim()
    46. String.prototype.trimEnd()
    47. String.prototype.trimStart()
    48. String.prototype.valueOf()
    49. String.prototype[@@iterator]()
    50. String.raw()
  5. 继承:
  6. Function
  7. 特性
    1. Function.arguments
    2. Function.caller
    3. Function.displayName
    4. Function.length
    5. Function.name
  8. 方法
    1. Function.prototype.apply()
    2. Function.prototype.bind()
    3. Function.prototype.call()
    4. Function.prototype.toSource()
    5. Function.prototype.toString()
  9. Object
  10. 特性
    1. Object.prototype.__proto__
    2. Object.prototype.constructor
  11. 方法
    1. Object.prototype.__defineGetter__()
    2. Object.prototype.__defineSetter__()
    3. Object.prototype.__lookupGetter__()
    4. Object.prototype.__lookupSetter__()
    5. Object.prototype.hasOwnProperty()
    6. Object.prototype.isPrototypeOf()
    7. Object.prototype.propertyIsEnumerable()
    8. Object.prototype.toLocaleString()
    9. Object.prototype.toSource()
    10. Object.prototype.toString()
    11. Object.prototype.valueOf()
    12. Object.setPrototypeOf()