• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

12
Views
Problem with Array.map Javascript method and string with accents

I noticed when i use ".map" on an array of strings with accent, there is a problem with the value of the current element. I don't understand why the second condition is false.

const types: string[] = ['Fée']

types.map(type => {
   const str = 'Fée'

   if(str === type){
       console.log(`str true : ${str}`)
   } 

   if(type === 'Fée'){
       console.log('type true')
   } else {
       console.log(`type false : ${type}`)
   }
})

In the console :

"str true : Fée"
"type false : Fée"

Moreover, this strange "é" can be saved in a JSON file (UTF-8 encoding). Here VSCode don't highlights the middle row: strange value in JSON file

about 1 month ago ·

Juan Pablo Isaza

2 answers
Answer question

0

One of your characters (é) is e\u0301 or \u0065\u0301, a LATIN SMALL LETTER E followed by COMBINING ACUTE ACCENT.

The other character (é) just \u00e9, a LATIN SMALL LETTER E WITH ACUTE.

You can tell that the strings are different also because of their .length.

To compare them, use .normalise():

const strings = ['Fée', 'Fée'];

console.log(strings[0] == strings[1]);
console.log(strings[0].normalize() == strings[1].normalize());

about 1 month ago · Juan Pablo Isaza Report

0

With a page like https://www.babelstone.co.uk/Unicode/whatisit.html you can see that the two are not actually equivalent.
The Fée from const str = 'Fée' is '\u0046\u0065\u0301\u0065' but the Fée from if(type === 'Fée'){ is '\u0046\u00e9\u0065'.

To fix this you can use unicode normalization with String.prototype.normalize.

const types: string[] = ['Fée']

types.map(type => {
   type = type.normalize('NFC')
   const str = 'Fée'.normalize('NFC')

   if(str === type){
       console.log(`str true : ${str}`)
   } 

   if(type === 'Fée'){
       console.log('type true')
   } else {
       console.log(`type false : ${type}`)
   }
})

about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.