Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove accents in an array of strings

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?

like image 519
Arnaud Stephan Avatar asked Jul 30 '17 10:07

Arnaud Stephan


People also ask

How do I remove diacritics accents from a string in Java?

Use java. text. Normalizer to handle this for you. This will separate all of the accent marks from the characters.

How do you remove accents in Python?

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.

How can I replace an accented character with a normal character in PHP?

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.


2 Answers

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 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.

var array = ['Enflure', 'Mongolie', 'Zimbabwe', 'Énorme', 'Éthiopie'];

array.sort((a, b) => a.localeCompare(b));

console.log(array);
like image 84
Nina Scholz Avatar answered Oct 02 '22 08:10

Nina Scholz


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"));
like image 43
Jonas Wilms Avatar answered Oct 02 '22 07:10

Jonas Wilms