Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: replace non breaking space and special space characters with ordinary space

I was trying to debug a problem of searching inside a string and it came down to the following interesting piece of code.

Both "item " and "item " seem equal but they are not!

var result = ("item " === "item ");

document.write(result);
console.log(result);

After investigating this further by pasting it on a Python interpreter, I found out that the first "item " has a different kind of space as "item\xc2\xa0". Which I think is a non breaking space.

Now, A possible solution to match these strings will be to replace \xc2\xa0 with space, but is there a better approach to convert all special space characters with normal space?.

like image 351
Irshad P I Avatar asked Jan 25 '23 10:01

Irshad P I


1 Answers

In ES2015/ES6 you can use the String.Prototype.normalize() method to decompose both characters to the same simple space character:

const normalize = str => str.normalize('NFKD');
console.log(normalize("item\u0020") === normalize("item\u00a0"));
like image 153
Kaiido Avatar answered Feb 05 '23 05:02

Kaiido