Is there a js function that replaces the xml Special Character with its escape sequence?

I search a lot on the Internet and did not find a js function that replaced the 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

are there any more? how about writing a hex value like 0 × 00,
is that also a problem?

+5
source share
5 answers

There is an interesting JS library here: Client-side encoding and decoding

+3
source

I used this:

function htmlSpecialChars(unsafe) {
    return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}
+9
source
+2
source

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

Accepted answer:

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

However, if you are using lodash, I like the cs01 answer from this post:

_.escape('fred, barney, & pebbles');
// => 'fred, barney, &amp; pebbles'
+1
source

These are the characters you need to worry about.

As a rule, you should use the DOM interface to create XML documents, then you do not need to worry about how to manually escape. This becomes a problem if you concatenate strings to build XML.

0
source