Get the App
SLTechnology News&Howtos  ›  Development  › 

How to reverse the meaning of string in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 10:32:15 09月28日 Update

In this article Xiaobian for you to introduce in detail "how to reverse the meaning of the string in JavaScript", the content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to reverse the meaning of the string in JavaScript" can help you solve your doubts.

There are no common methods to escape and reverse escape strings in JavaScript, such as encodeURI (decodeURI) and encodeURIComponent (decodeURIComponent).

But how do you reverse escape HTML in JavaScript? For example, the following code:

Var jsonData = {

Title: ""

Desc: ""

Image: ""

}

The wrapped part is the value returned from the server (the code in the above example is taken from the code of the ejs template of Express in Node.js). If the string returned from the server contains quotation marks, such as single or double quotes, there will be an error when the above JS code is interpreted in the browser. How to solve this problem?

The basic idea is to reverse the string through the innerHTML attribute of the DOM element on the page, and then return the value to the variable of JavaScript. Look at the following two pieces of code:

1. Native JavaScript writing:

Function htmlDecode (input) {

Var e = document.createElement ('div')

E [XSS _ clean] = input

Return e.childNodes.length = = 0? "": e.childNodes [0] .nodeValue

}

HtmlDecode ("

")

2. JQuery:

Function htmlDecode (value) {

Return $('). Html (value). Text ()

}

The first function creates a DIV element using the native JavaScript method, then assigns the string that needs to be reversed to its innerHTML attribute, and finally returns the value of the nodeValue attribute of the DIV element. The second function uses JQuery's method, which is based on the same principle as the first function. Because the DIV elements are only created in memory and do not append or inert to the page, there is no impact on the existing page.

Finally, we changed the initial code to the following way:

Var jsonData = {

Title: $('') Html ("). Text ()

Desc: $('') Html ("). Text ()

Image: ""

}

This allows HTML anti-escape of the string returned by the server in JavaScript.

After reading this, the article "how to reverse the meaning of a string in JavaScript" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it. If you want to know more about the article, please follow the industry information channel.

Tags: Characters strings codes elements methods functions attributes quotes articles pages services content writing ideas proper same memory principles variables just Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Huawei Shulou Tech Info MariaDB macOS