The common method of escaping and inverting strings in JavaScript is to use encodeURI (decodeURI), encodeURIComponent (decodeURIComponent), Specific use methods and differences.
But how do you invert HTML in JavaScript? For example, the following code:
var jsondata = {
title: "<%= data.name?" Data.name:title%> ",
desc:" <%= data.content? Data.content: '%> ',
Image: "<%-data.img?" Data.img: '%> '
};
Where <%=%> is wrapped is the value that is returned from the service side (the code in the example above is taken from the code of the Ejs template of the Express in Node.js). If the string returned from the service side contains quotes, such as single or double quotes, the JS code above will be incorrectly interpreted in the browser. How to solve this problem?
The basic idea is to invert the string HTML by the innerHTML property of the DOM element on the page, and then return the value to the JavaScript variable. Look at the following two pieces of code:
1. Native JavaScript notation:
function HtmlDecode (input) {
var e = document.createelement (' div ');
e.innerhtml = 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 creates a DIV element using the native JavaScript method, assigns the string that needs to be inverted to its innerHTML property, and finally returns the value of the NodeValue property of the DIV element. The second function uses the method of jquery, which is the same as the first function. Because the DIV element is created in memory only and is not append or inert to the page, it does not have any effect on the existing page.
Finally, we'll change the first piece of code to the following way:
var jsondata = {
title: $ (' <div/> '). HTML ("<%= data.name? Data.name:title%> "). Text (),
desc: $ (' <div/> '). HTML (" <%= data.nontent? Data.nontent: '%> '). Text (),
Image: "<%-data.img?" Data.img: '%> '
};
This allows you to perform HTML-reverse manipulation of the string returned by the server-side in JavaScript.
The above in JavaScript in the HTML to reverse the meaning of the text is small to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.