Method 1:
Use the browser's internal converter to achieve conversion. The key is to dynamically create a container tag 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, that is, the string converted by HTML encoding is obtained. When displaying, it can be reversed (actually, there is no need to convert when displaying, and it can be displayed normally by assigning the value directly to the div) of).
]
Second method: Regular Replace
by converting <> and space characters into html encoding through regular expressions. Since this method is not built-in in the system, it is easy for some special tags to not be replaced, and it is inefficient
If you need to introduce external Js, you need to refresh it to execute
]
You can run the test first , I also discovered that the first method is more useful. It’s really good. You must remember it.
In addition, there are some htmlencode functions used by some editors. You can add them as needed. However, you need to be reminded that the code must be tested. When the webmaster of Script House jb51.net posted this message, the test was indeed very difficult. Trouble, I have modified it many times
Copy code
The 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,"
");
text = text.replace(/t/g," "");
return text;
}
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn