Method 1:
The key to using the browser internal converter to implement conversion is to dynamically create a container tag element, such as DIV, set the string to be converted to the innerText(ie supported)||textContent(Firefox supported), and then return the innerHTML of this element, that is, get the string converted by HTML encoding, and it is fine when displayed (in fact, it is not necessary to convert when displayed, and directly assign the value to the div to display normally).
[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]
The second method: regular replacement
By converting the regular expression to html encoding, since this method is not built-in to the system, it is easy to cause some special tags to be replaced without replacement, and the efficiency is inefficient
[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]
You can run the test first, and I also found that the first method is more useful. It's really good, everyone must remember it.
In addition, some htmlencode functions used by some editors. You can add them as needed. However, it should be noted that the code must be tested. I am really troublesome to test when the webmaster posted this information. I have modified it many times.
Copy the codeThe code is as follows:
function HTMLEncode(text){
text = (/&/g, "&") ;
text = (/"/g, """) ;
text = (/</g, "<") ;
text = (/>/g, ">") ;
//text = (/\ /g," ");
text = (/\n/g,"<br>");
text = (/\t/g," ");
return text;
}