查看 DIV 等 HTML 元素并用 HTML 元素替换特定文本片段的最佳方法是什么。例如,假设我们有 token [b]
和[/b]
。我想将它们替换为 <b>
和</b>
,分别。
我最接近的例子是下面的例子。
HTML 到 teplace:
<div id="response">This is some [b]GREAT[/b] stuff!</div>
<小时/>
示例#1:
$('#response').html(function() {
return $(this).text().replace('[b]', '<b>');
});
$('#response').html(function () {
return $(this).text().replace('[/b]', '</b>');
});
结果#1:
<小时/>This is some GREAT stuff!
示例#2:
$('#response').html(function() {
return $(this).text().replace('[b]', $('<b>'));
});
$('#response').html(function () {
return $(this).text().replace('[/b]', $('</b>'));
});
结果#2:
<小时/>This is some [object Object]GREAT[object Object] stuff!
期望的结果:
This is some GREAT stuff!
两者都不起作用。前者只是将 token 替换为空,而后者则将其替换为浏览器中的对象,而不是所需的 HTML 元素。
最佳答案
使用正则表达式应该效果很好:
$('#response').html(function() {
return $(this).text().replace(/\[(\/?\w+)\]/g, "<$1>");
});
好处是所有 token 都可以被替换,而无需单独命名它们。
请注意,这为跨站点脚本攻击打开了大门!
<小时/>如果您想在此过程中转换 token (例如 [b]
到 <strong>
)并将它们列入白名单(并且您肯定希望将它们列入白名单以缓解 XSS 漏洞),请使用回调函数作为替换,如下所示:
$('#response').html(function () {
var map = {
b: "strong",
i: "em",
p: "p"
};
return $(this).text().replace(/\[(\/?)(\w+)\]/g, function ($0, $1, $2) {
if (map.hasOwnProperty($2)) {
return "<" + $1 + map[$2] + ">";
} else {
return $0;
}
});
});
<小时/>
为了使其成为 jQuery 答案,以下是如何将所有这些变成一个精美的 jQuery 插件以供重复使用:
$.fn.extend({
unphpbb: (function () {
var map = {
b: "strong",
i: "em",
p: "p"
},
tokens = /\[(\/?)(\w+)\]/g,
replacement = function ($0, $1, $2) {
return map.hasOwnProperty($2) ? "<" + $1 + map[$2] + ">" : $0;
},
replaceTokens = function (i, html) {
return html.replace(tokens, replacement);
};
return function () {
return this.html(replaceTokens);
};
})()
});
用作
$("#response").unphpbb();
<小时/>
当然,在服务器上使用 bbcode 解析器并向客户端发送经过适当处理的 HTML 是解决此问题的首选方法。在客户端上使用上述函数执行此操作在各个方面都是较差的。
关于javascript - 用 HTML 元素替换文本标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22850720/