简体   繁体   中英

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

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?

I have used this:

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

这里有一个有趣的 JS 库: Client side HTML encoding anddecode

您可以使用PHPJS 项目中的PHP htmlspecialchars

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'

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM