Wryte
Wryte

Reputation: 895

How do I replace unicode character u00A0 with a space in javascript?

I'm looking to replace a bad character that a content editable div uses when a space is added at the end of the input.

Here is what I've tried

var text = $(this).text();
text.replace(/\u00A0/, " ");

But when I check the value of the last character like this

text.charCodeAt(text.length-1)

The value is still 160 instead of 32

Upvotes: 5

Views: 26385

Answers (1)

jcubic
jcubic

Reputation: 66590

In javascript strings are immutable and replace return new string, try this:

var text = $(this).text();
text = text.replace(/\u00A0/, " ");

or in one line:

var text = $(this).text().replace(/\u00A0/, " ");

also if you want to replace all instances of the character, you need to add g flag to the regex /\u00A0/g.

Upvotes: 12

Related Questions