Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.
El método localeCompare()
devuelve un número que indica si la cadena de caracteres actual es anterior, posterior o igual a la cadena pasada como parámetro, en orden lexicográfico.
Los nuevos argumentos locales
y options
permiten a las aplicaciones especificar el idioma y el orden de clasificación que debe usarse y personalizar el comportamiento de la función. En las implementaciones más antiguas, que ignoran los argumentos locales
y options
, la configuración locale
y el orden de clasificación utilizados dependen enteramente de la implementación
Sintaxis
referenceStr.localeCompare(compareString[, locales[, options]])
Parámetros
Comprueba la sección Compatibilidad con el navegador para ver que navegadores soportan los argumentos locales
y options
, and the Checking for support for locales
and options
arguments for feature detection.
compareString
- La cadena con la que queremos comparar la cadena actual de caracteres.
locales
-
Optional. A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the
locales
argument, see the Intl page. The following Unicode extension keys are allowed:co
- Variant collations for certain locales. Possible values include:
"big5han"
,"dict"
,"direct"
,"ducet"
,"gb2312"
,"phonebk"
,"phonetic"
,"pinyin"
,"reformed"
,"searchjl"
,"stroke"
,"trad"
,"unihan"
. The"standard"
and"search"
values are ignored; they are replaced by theoptions
propertyusage
(see below). kn
- Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are
"true"
and"false"
. This option can be set through anoptions
property or through a Unicode extension key; if both are provided, theoptions
property takes precedence. kf
- Whether upper case or lower case should sort first. Possible values are
"upper"
,"lower"
, or"false"
(use the locale's default). This option can be set through anoptions
property or through a Unicode extension key; if both are provided, theoptions
property takes precedence.
options
-
Optional. An object with some or all of the following properties:
localeMatcher
- The locale matching algorithm to use. Possible values are
"lookup"
and"best fit"
; the default is"best fit"
. For information about this option, see the Intl page. usage
- Whether the comparison is for sorting or for searching for matching strings. Possible values are
"sort"
and"search"
; the default is"sort"
. sensitivity
-
Which differences in the strings should lead to non-zero result values. Possible values are:
"base"
: Only strings that differ in base letters compare as unequal. Examples:a ≠ b
,a = á
,a = A
."accent"
: Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples:a ≠ b
,a ≠ á
,a = A
."case"
: Only strings that differ in base letters or case compare as unequal. Examples:a ≠ b
,a = á
,a ≠ A
."variant"
: Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples:a ≠ b
,a ≠ á
,a ≠ A
.
The default is
"variant"
for usage"sort"
; it's locale dependent for usage"search"
. ignorePunctuation
- Whether punctuation should be ignored. Possible values are
true
andfalse
; the default isfalse
. numeric
- Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are
true
andfalse
; the default isfalse
. This option can be set through anoptions
property or through a Unicode extension key; if both are provided, theoptions
property takes precedence. Implementations are not required to support this property. caseFirst
- Whether upper case or lower case should sort first. Possible values are
"upper"
,"lower"
, or"false"
(use the locale's default); the default is"false"
. This option can be set through anoptions
property or through a Unicode extension key; if both are provided, theoptions
property takes precedence. Implementations are not required to support this property.
Valor devuelto
Un número negativo si la cadena de referencia ocurre antes de la cadena de comparación; positivo si la cadena de referencia ocurre después de la cadena de comparación; 0 si son equivalentes.
Descripción
Returns an integer indicating whether the referenceStr comes before, after or is equivalent to the compareStr.
- Negative when the referenceStr occurs before compareStr
- Positive when the referenceStr occurs after compareStr
- Returns 0 if they are equivalent
NO CONFIAR en que los valores devueltos sean siempre -1 o 1. Los resultados de enteros negativos y positivos varían entre los navegadores (así como entre diferentes versiones de un mismo navegador) porque la especificación W3C solo exige valores negativos y positivos. Algunos navegadores pueden devolver -2 o 2 o incluso algún otro valor negativo o positivo.
Ejemplos
Uso de localeCompare()
// La letra "a" es anterior a la "c" produciendo un valor negativo 'a'.localeCompare('c'); // -2 o -1 (u otro valor negativo) // Alfabeticamente la palabra "check" viene después de "against" produciendo un valor ppositivo 'check'.localeCompare('against'); // 2 o 1 (u otro valor positivo) // "a" y "a" son equivalentes produciendo un valor neutro de 0 'a'.localeCompare('a'); // 0
Ordenar un array
localeCompare
enables a case-insensitive sort of an array.
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu']; items.sort((a, b) => a.localeCompare(b)); // ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
Verificar si el navegador soporta argumentos extendidos
The 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; }
Uso de 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
Uso de 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
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
property.
Especificaciones
Especificación | Estado | Comentario |
---|---|---|
ECMAScript 3rd Edition (ECMA-262) | Standard | Definición inicial. Implementado en JavaScript 1.2. |
ECMAScript 5.1 (ECMA-262) La definición de 'String.prototype.localeCompare' en esta especificación. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) La definición de 'String.prototype.localeCompare' en esta especificación. |
Standard | |
ECMAScript Latest Draft (ECMA-262) La definición de 'String.prototype.localeCompare' en esta especificación. |
Draft | |
ECMAScript Internationalization API 1.0 (ECMA-402) La definición de 'String.prototype.localeCompare' en esta especificación. |
Standard | Definiciones de los parámetros locale y option . |
ECMAScript Internationalization API 2.0 (ECMA-402) La definición de 'String.prototype.localeCompare' en esta especificación. |
Standard | |
ECMAScript Internationalization API 4.0 (ECMA-402) La definición de 'String.prototype.localeCompare' en esta especificación. |
Draft |
Compatibilidad con el navegador
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Soporte básico | Chrome Soporte completo Si | Edge Soporte completo Si | Firefox Soporte completo 1 | IE Soporte completo Si | Opera Soporte completo Si | Safari Soporte completo Si | WebView Android Soporte completo Si | Chrome Android Soporte completo Si | Edge Mobile Soporte completo Si | Firefox Android Soporte completo 4 | Opera Android Soporte completo Si | Safari iOS Soporte completo Si | Samsung Internet Android Soporte completo Si | nodejs Soporte completo Si |
locales | Chrome Soporte completo 24 | Edge Soporte completo Si | Firefox Soporte completo 29 | IE Soporte completo 11 | Opera Soporte completo 15 | Safari Soporte completo 10 | WebView Android Sin soporte No | Chrome Android Soporte completo 26 | Edge Mobile ? | Firefox Android Sin soporte No | Opera Android Sin soporte No | Safari iOS Soporte completo 10 | Samsung Internet Android Soporte completo Si | nodejs ? |
options | Chrome Soporte completo 24 | Edge Soporte completo Si | Firefox Soporte completo 29 | IE Soporte completo 11 | Opera Soporte completo 15 | Safari Soporte completo 10 | WebView Android Sin soporte No | Chrome Android Soporte completo 26 | Edge Mobile ? | Firefox Android Sin soporte No | Opera Android Sin soporte No | Safari iOS Soporte completo 10 | Samsung Internet Android Soporte completo Si | nodejs ? |
Leyenda
- Soporte completo
- Soporte completo
- Sin soporte
- Sin soporte
- Compatibility unknown
- Compatibility unknown