The usual way to escape and invert strings in JavaScript is to use encodeURI (decodeuri),encodeuricomponent ( decodeURIComponent) These methods, the specific use of methods and differences can refer to this article http://qianduanblog.com/post/ Js-learning-34-en-decodeuri-en-decodeuricomponent-un-escape-btoa-atob.html
But how do you reverse-manipulate HTML in JavaScript? For example, the following code:
var jsondata = { "<%= data.name? Data.name:title%>", "<%= data.content?" Data.content: '%> ' ,' <%-data.img? data.img: '%> '};
Where <%=%> is wrapped up is the value returned from the server (the code in the previous example is taken from the code of the ejs template in Express in node. js ). If the string returned from the server contains quotation marks, such as single quotes or double quotes, then the above JS code will be interpreted in the browser error. How to solve this problem?
The basic idea is to use the InnerHTML property of the DOM element on the page to invert the string to HTML and return the value to the JavaScript variable. Look at the following two sections of code:
1. Native JavaScript notation:
function HtmlDecode (input) { var e = document.createelement (' div '); = input; return e.childnodes.length = = = 0? "": E.childnodes[0].nodevalue;} HtmlDecode (
2. jquery notation:
function HtmlDecode (value) { return $ (' <div/> '). HTML (value). text ();}
The first function uses the native JavaScript method to create a DIV element, then assigns the string that needs to be reversed to its innerHTML property, and finally returns the value of the NodeValue property of the DIV element. The second function uses the JQuery method, which has the same basic principle as the first function. Since DIV elements are only created in memory and not append or inert to the page, there is no impact on existing pages.
Finally, we changed the code from the beginning to the following:
var jsondata = { title: $ (' <div/> '). HTML ("<%= data.name? Data.name:title%> "). Text (), desc: $ (' <div/> '). HTML (" <%= data.nontent? Data.nontent: "%>"). Text (), "<%-data.img?" Data.img: '%> '};
This allows you to perform HTML inversion of the string returned by the server side in JavaScript.
To invert HTML in JavaScript