Eduard Luca
Eduard Luca

Reputation: 6611

JavaScript RegEx to replace HTML encoding

I have the following JS code, which I want to replace all my ₪ (₪) with a $ sign.

$(this).html($(this).html().replace(/₪/g,'$'));

However it's not doing anything. I've also tried to escape the special characters (as I don't know exactly which need to and which don't), but that didn't work either.

Upvotes: 0

Views: 2095

Answers (2)

Andy E
Andy E

Reputation: 344695

Browsers recreate the HTML as a representation of the DOM when you access innerHTML (or jQuery's html()). This means characters that may have been encoded in the original HTML will be encoded in the output for innerHTML only if necessary to ensure the resulting HTML can be parsed. Since is not a syntactic part of HTML's structure, it won't be encoded.

tl;dr, replace the literal character:

.replace(/₪/g,'$')

Alternatively, if you're not sure about the encoding of your file, use the Unicode escape sequence:

.replace(/\u20AA/g,'$')

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150080

The regex syntax to match on a unicode hex character code is:

\uhhhh

Where the h's represent a four-digit hex code So:

$(this).html($(this).html().replace(/\u8362;/g,'$'));

// OR if that number was a decimal number, in hex you'd have:
$(this).html($(this).html().replace(/\u20AA;/g,'$'));

Upvotes: 2

Related Questions