Search code examples
javascriptregexreplacehtml-encode

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.


Solution

  • 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,'$')