最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove accents in an array of strings - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 8

You 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 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);

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"));
发布评论

评论列表(0)

  1. 暂无评论