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?
Use java. text. Normalizer to handle this for you. This will separate all of the accent marks from the characters.
We can remove accents from the string by using a Python module called Unidecode. This module consists of a method that takes a Unicode object or string and returns a string without ascents.
php $transliterator = Transliterator::createFromRules(':: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD); $test = ['abcd', 'èe', '€', 'àòùìéëü', 'àòùìéëü', 'tiësto']; foreach($test as $e) { $normalized = $transliterator->transliterate($e); echo $e.
You could use String#localeCompare
.
The
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 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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With