Question

I know there is a function called String.prototype.localeCompare which you can use, and you can send in as the second argument a list of locales.

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

But if you look at the browser compatibility table, only Chrome supports it.

enter image description here

How do you sort or compare Strings in JavaScript based on a certain locale?

How does all the big websites do this, like ebay or amazon? They must have some kind of String sorting in the front-end.. right?

Was it helpful?

Solution

May be you need sorting, not compare?

Javascript array sort method sort strings on its Unicode(not ASCII) codes. You can sort array of strings to get it in alphabetical order.

['Собака', 'Кошка'].sort() will sort array to ["Кошка", "Собака"] which is right in Ru_ru locale.

You can add compare function like this:

['Собака', 'Кошка', 'Свекла'].sort(function(a, b) { 
    return a[1] > b[1]?1:-1;
})

Javascript will compare strings by Unicode character by character. In my example compare is inside a[1] > b[1] on native low-level code. Return -1 or 1 needs for sort function to replace array elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top