[Escape characters] HTML character entities & lt; & gt: & amp; etc.

During development, the url obtained by javascript from the background will be escaped, such as: http://localhost:8080/Home/Index?a=14&b=15&c=123, I want to convert it to http:/ /localhost:8080/Home/Index?a=14&b=15&c=123

I found the solution online for a long time:

Escape is divided into escapeHTML and unescapeHTML. Let's first look at the implementation of the two functions.

/**
 * @function escapeHTML escape html script < > & " '
 * @param a -
 * string
 */
escapeHTML: function(a){
    a = "" + a;
    return a.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");;
},
/**
 * @function unescapeHTML restore html script < > & " '
 * @param a -
 * string
 */
unescapeHTML: function(a){
    a = "" + a;
    return a.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'");
},
1, escapeHTML converts < > & " ' into character entities 
usage scenarios: 
(1) The user enters in the page (such as an input box) <script>alert(2);</script>, js submits the content to the backend When saving 
(2) display, the back end returns the string to the front end; after js is received: 
a, use escapeHTML to convert the string to <script>alert(2);</script> At this point, the browser will It can be parsed correctly, because after the browser receives the entity character, it will be converted into the corresponding angle brackets, etc. 
b, without using escapeHTML, when the browser sees <, it will consider it as the beginning of the html tag, and directly treat the string just now as a script Executed, this is the xss vulnerability. 

2, unescapeHTML converts character entities into < > & " ' 
usage scenario: 
the backend displays the escaped content to the page; for example <script>alert(2);</ After the script> 
js is received: 
a, the front end performs unescapeHTML, and the DOM operation can be performed directly to display the label on the page. 

b. If there is no unescapeHTML in the front end, <script>alert(2);</script> is output as it is, but it is not executed at this time. 

Escape characters: 

caefd511-7ae6-3a26-889a-1c741607510e.jpg (436×454)

Tip: The advantage of using entity names instead of numbers is that the names are easier to remember. The downside, though, is that browsers may not support all entity names (it does support entity numbers well).


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326693578&siteId=291194637