js html代码转义,JS实现HTML标签转义及反转义
时间: 2024-01-02 07:03:53 浏览: 105
JS实现HTML标签转义:
```javascript
function escapeHTML(htmlStr) {
return htmlStr.replace(/[&<>"']/g, function(match) {
switch (match) {
case "&":
return "&";
case "<":
return "<";
case ">":
return ">";
case "\"":
return """;
case "'":
return "'";
default:
return match;
}
});
}
```
JS实现HTML标签反转义:
```javascript
function unescapeHTML(htmlStr) {
var temp = document.createElement("div");
temp.innerHTML = htmlStr;
var result = temp.childNodes[0].nodeValue;
temp.removeChild(temp.firstChild);
return result;
}
```
使用示例:
```javascript
var htmlStr = '<div id="test">Hello World!</div>';
var escapedStr = escapeHTML(htmlStr); // <div id="test">Hello World!</div>
var unescapedStr = unescapeHTML(escapedStr); // <div id="test">Hello World!</div>
```
阅读全文