7

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  
&                   &           Ampersand sign 
'                   '          Single quote 
"                   "          Double quote
>                   >            Greater than 
<                   &lt;            Less than

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

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
  • possible duplicate of [how to escape xml entities in javascript?](http://stackoverflow.com/questions/7918868/how-to-escape-xml-entities-in-javascript) – sudhansu63 Sep 22 '15 at 08:30

6 Answers6

13

I have used this:

function htmlSpecialChars(unsafe) {
    return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&apos;");
}
Ollie
  • 1,641
  • 1
  • 13
  • 31
nathanjosiah
  • 4,441
  • 4
  • 35
  • 47
3

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

Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
2

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

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
1

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'
Andrew
  • 2,368
  • 1
  • 23
  • 30
0

This is old, but my favorite way to do it is to let the browser figure it out:

function encodeXML(data){
    var d = document.createElement('div');
    d.appendChild(document.createTextNode(data));
    return d.innerHTML;
}

encodeXML('&');

Output:

"&amp;"

You could also use d.innerText = data; or d.textContent = data;, but createTextNode() has the most browser support.

ADJenks
  • 2,973
  • 27
  • 38
0

Those are the only characters you need to worry about.

Generally you should be using a DOM interface to build XML documents then you don't need to worry about manually escaping things. That only becomes an issue if you are mashing together strings to build the XML.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335