简体   繁体   中英

Character escape in Javascript

I have a String in javascript that corresponds to an xml, which, when assigning it as a property value, escapes me the quotes with &quot; , but I need it to also escape the "<" and ">" signs, which not doing.

This is an example of the xml:

<row row="0" XMLContent="<?xml version='1.0' encoding='UTF-8'>"></row>

I decided to do it with a replace:

value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
m_row.attributes.getNamedItemNS(null, name).value = value;

But by doing this you are assigning it like this:

<row row="0" XMLContent="&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; &amp;gt;"></row>

The code's ampersand to escape "<" and ">" is being escaped as well, making it look like this:

From "&lt;" to "&lt;" and the same for "&gt;" so when I take the value of that attribute and try to parse it to XML, it gives me an error, as it cannot be interpreted.

I would greatly appreciate an answer.

Such case you can use &lt and &gt

<row row="0" XMLContent="&lt?xml version='1.0' encoding='UTF-8'&gt"></row>

If you're using DOM to read/write the XML then you do not need the replace. The serializer will take care of the escaping.

You're replace will result in double escaping for < and > .

 const xmlDocument = (new DOMParser()).parseFromString( '<row row="0" XMLContent=""/>', 'text/xml' ); const row = xmlDocument.documentElement; row.setAttributeNS(null, "XMLContent", "<?xml version='1.0' encoding='UTF-8'?><demo/>"); const xmlString = (new XMLSerializer()).serializeToString(xmlDocument); console.log(xmlString);

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