In JavaScript, the common method is to use encodeURI (decodeURI) and encodeURIComponent (decodeURIComponent). The specific usage methods and differences are used.
But how to inversely escape 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 : '' %>"};The part wrapped in <%= %> is the value returned from the server (the code in the above example is taken from the code of the Express ejs template in Node.js). If the string returned from the server contains quotes, such as single or double quotes, then the above JS code will have an error when interpreting it in the browser. How to solve this problem?
The basic idea is to invert the string HTML through the innerHTML attribute of the DOM element on the page, and then return the value to the JavaScript variable. Look at the following two codes:
1. Native JavaScript writing method:
function htmlDecode(input){ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;}htmlDecode("<img src='myimage.jpg'>");2. JQuery writing method:
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 inversely escaped to its innerHTML property, and finally returns the value of the nodeValue property of the DIV element. The second function uses JQuery's method, and its basic principles are the same as the first function. Since DIV elements are only created in memory and are not append or inert to the page, they will not have any impact on the existing page.
Finally, we change the initial code to the following method:
var jsonData = { title: $('<div/>').html("<%= data.name? data.name : title %>").text(), desc: $('<div/>').html("<%= data.notent? data.notent : '' %>").text(), image: "<%- data.img? data.img : '' %>"};This allows HTML inversion of strings returned by the server in JavaScript.
The above detailed explanation of the reverse escape of HTML in JavaScript is all the content I share with you. I hope it can give you a reference and I hope you can support Wulin.com more.