Compare non English characters in string

Viewed 449

I need to compare non english strings as below

Majsstärkelse unicode - Majsstärkelse

Majsstärkelse unicode - Majsstärkelse

if I compare like this

if('Majsstärkelse' === 'Majsstärkelse')

Some of characters not working this comparison.So i tried with

const collator = new Intl.Collator('de')
const order = collator.compare('Ü', 'ß')
console.log(order)

But still no success result. How can I achieve this

1 Answers

You can use String.protoype.normalize to normalize canonically equivalent strings.

a='Majsst\u{00E4}rkelse'
b='Majssta\u{0308}rkelse'
console.log(a,b)
console.log(a === b)
console.log(a.normalize('NFC')===b.normalize('NFC'))

Note: the strings you have are escaped. The above is for comparing unescaped strings.
Code to decode from unicode HTML entities first:

const decodeUEntities = u=>u.replace(/&#(x[\dA-F]+|\d+);/g,
  (_,u)=>String.fromCodePoint(u[0]==='x'?parseInt(u.substr(1),16):+u))

str1 = decodeUEntities("Majsstärkelse")
str2 = decodeUEntities("Majsstärkelse")

// decode unicode HTML entities, if you want named HTML entities too, find a list of them and add them to the replacement code, for simplicty I will be leaving that out
console.log(str1, str2, str1===str2)

console.log(str1.normalize('NFC'),str2.normalize('NFC'),
            str1.normalize('NFC')===str2.normalize('NFC'))

Related