Sometimes we will <> this type of characters in html, and we need to convert it into html character encoding for ease of use. Let's look at an example below.
An html string is a string with special html characters such as '<div id = "a"> aklsdjfklsjdfl </div>, we usually need to process it before outputting it so as not to output it into a real html element, that is, to convert <into html symbol code like <.
If the string is long and contains many special characters, how can we simply and efficiently transcode all of them? Loop? Regular Expression? No! See:
The Code is as follows: |
Copy code |
Function bian (a) {return new Option (a). innerHTML} |
This is all! Usage:
The Code is as follows: |
Copy code |
Function bian (a) {return new Option (a). innerHTML} Var a = '<div id = "a"> aklsdjfklsjdfl </div> '; Alert (bian ()); |
By replacing special characters
1) HTML encoding:
The Code is as follows: |
Copy code |
Function HTMLEnCode (str) { Var s = ""; If (str. length = 0) return ""; S = str. replace (/&/g, "& gt ;"); S = s. replace (/</g, "& lt ;"); S = s. replace (/>/g, "& gt ;"); S = s. replace (// g, "& nbsp ;"); S = s. replace (/'/g ,"'"); S = s. replace (/"/g," & quot ;"); S = s. replace (/n/g, "<br> "); Return s; } |
2) HTML Decoding:
The Code is as follows: |
Copy code |
Function HTMLDeCode (str) { Var s = ""; If (str. length = 0) return ""; S = str. replace (/& gt;/g ,"&"); S = s. replace (/& lt;/g, "<"); S = s. replace (/& gt;/g, "> "); S = s. replace (/& nbsp;/g ,""); S = s. replace (/'/g ,"'"); S = s. replace (/& quot;/g ,"""); S = s. replace (/<br>/g, "n "); Return s; } |