I have an array of strings, like so
let array = ['Enflure', 'Énorme', 'Zimbabwe', 'Éthiopie', 'Mongolie']
I want to sort it alphabetically, so I use array.sort()
, and the result I get is :
['Enflure', 'Mongolie', 'Zimbabwe', 'Énorme', 'Éthiopie']
I guess the accents are the problems here, so I would like to replace the É
with an E
all over my array.
I tried this
for (var i = 0; i < (array.length); i++) {
array[i].replace(/É/g, "E");
}
But it didn't work. How could I do this?
I have an array of strings, like so
let array = ['Enflure', 'Énorme', 'Zimbabwe', 'Éthiopie', 'Mongolie']
I want to sort it alphabetically, so I use array.sort()
, and the result I get is :
['Enflure', 'Mongolie', 'Zimbabwe', 'Énorme', 'Éthiopie']
I guess the accents are the problems here, so I would like to replace the É
with an E
all over my array.
I tried this
for (var i = 0; i < (array.length); i++) {
array[i].replace(/É/g, "E");
}
But it didn't work. How could I do this?
Share Improve this question edited Jul 30, 2017 at 11:01 Gerardo Furtado 102k9 gold badges128 silver badges177 bronze badges asked Jul 30, 2017 at 10:07 Arnaud StephanArnaud Stephan 4014 silver badges17 bronze badges 2- 3 Small note: remove the -1 – Jonas Wilms Commented Jul 30, 2017 at 10:08
- Try semplicewebsites./removing-accents-javascript – Stuart Commented Jul 30, 2017 at 10:09
2 Answers
Reset to default 8You could use String#localeCompare
.
The
localeCompare()
method returns a number indicating whether a reference string es before or after or is the same as the given string in sort order.The new
locales
andoptions
arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore thelocales
andoptions
arguments, the locale and sort order used are entirely implementation dependent.
var array = ['Enflure', 'Mongolie', 'Zimbabwe', 'Énorme', 'Éthiopie'];
array.sort((a, b) => a.localeCompare(b));
console.log(array);
JS strings are not mutable. That means that replace doesnt replace on the original string, but returns a new one:
for (var i = 0; i <(array.length); i++) {
array[i]=array[i].replace(/É/g,"E");
}
Or shorter:
array=array.map(s=>s.replace(/É/g,"E"));