Method 1:
Use a browser internal converter to implement conversion. The essentials are to dynamically create a container label element, such as DIV, and set the string to be converted to the innerText of this element (ie supported) | textContent (supported by Firefox), and then returns the innerHTML of this element to obtain the HTML-encoded string, which can be displayed in turn (in fact, the conversion is not needed when the display is complete, directly assign a value to the div to display it normally ).
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Method 2: Regular Expression replacement
The regular expression is used to convert <> and space characters into html encoding. Because this method is not built-in to the system, it is easy to see that some special labels are not replaced, and the efficiency is low.
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
You can run the test first. I also found that the first method is quite easy to use. It's really good. You must remember it.
In addition, some htmlencode functions used by some editors will be added as needed. However, you must note that the Code must be tested, it was really troublesome to test this information when the jb51.net webmaster posted it. It was modified several times.
Copy codeThe Code is as follows:
Function HTMLEncode (text ){
Text = text. replace (/&/g ,"&");
Text = text. replace (/"/g ,""");
Text = text. replace (/</g, "<");
Text = text. replace (/>/g, "> ");
// Text = text. replace (// \/g ,"");
Text = text. replace (/\ n/g, "<br> ");
Text = text. replace (/\ t/g ,"");
Return text;
}