Is there js function that replace xml Special Character with their escape sequence?

16,333

Solution 1

There's an interesting JS library here: Client side HTML encoding and decoding

Solution 2

I have used this:

function htmlSpecialChars(unsafe) {
    return unsafe
    .replace(/&/g, "&")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&apos;");
}

Solution 3

You could use PHP's htmlspecialchars from the PHPJS project.

Solution 4

This is similar to Can I escape html special chars in javascript?

The accepted answer there is this:

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

However, if you're using lodash, then I like cs01's answer from that post:

_.escape('fred, barney, & pebbles');
// => 'fred, barney, &amp; pebbles'
Share:
16,333
Dor Cohen
Author by

Dor Cohen

C# and web developer

Updated on June 09, 2022

Comments

  • Dor Cohen
    Dor Cohen almost 2 years

    I search the web alot and didn't find js function that replace xml Special Character with their escape sequence?
    Is there something like this?

    I know about the following:

    Special Character   Escape Sequence Purpose  
    &                   &amp;           Ampersand sign 
    '                   &apos;          Single quote 
    "                   &quot;          Double quote
    >                   &gt;            Greater than 
    <                   &lt;            Less than
    

    is there more? what about writing hexadecimal value like 0×00,
    Is this also a problem?