我想通过JavaScript函数将文本显示为HTML。如何在JavaScript中转义HTML特殊字符?有API吗?
当前回答
使用Lodash:
_.escape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'
源代码
其他回答
找到一个更好的解决方案是很有趣的:
var escapeHTML = function(unsafe) {
return unsafe.replace(/[&<"']/g, function(m) {
switch (m) {
case '&':
return '&';
case '<':
return '<';
case '"':
return '"';
default:
return ''';
}
});
};
我没有解析>,因为它没有破坏结果中的XML/HTML代码。
以下是基准测试:http://jsperf.com/regexpairs 此外,我还创建了一个通用转义函数:http://jsperf.com/regexpairs2
你可以对字符串中的每个字符进行编码:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
或者只关注主要角色(&,inebreaks, <, >, "和'),比如:
函数编码(r) { 返回r.replace (/ [\ x26 \ x0A \ < > "] / g函数(r){返回" & # + r.charCodeAt(0) +”;“}) } 测试。value=encode('如何编码\nonly html标签&<>\'" nice & fast!'); /************* * \x26是& &号(必须排在第一位), * \x0A为换行符, *************/ < textarea测试行id = =“9”关口= " 55 " > & # 119;& # 119;& # 119;& # 46;& # 87;& # 72;& # 65;& # 75;& # 46;& # 99;& # 111;& # 109;textarea > < /
在JavaScript中删除字符串中的HTML标签:
const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
显示未编码文本的最简洁和有效的方法是使用textContent属性。
比使用innerHTML更快。这还没有考虑到逃逸开销。
document.body.textContent = 'a <b> c </b>';
这里有一个几乎适用于所有浏览器的解决方案:
function escapeHtml(unsafe)
{
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
如果你只支持现代浏览器(2020+),那么你可以使用新的replaceAll函数:
const escapeHtml = (unsafe) => {
return unsafe.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');
}
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?