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
Juan Pablo Isaza
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());
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}`)
}
})