我正在使用 JavaScript 来设置输入的值,其中文本可能包含 HTML 特定字符,例如 &
等。所以,我试图找到一个匹配这些值的正则表达式,并分别用适当的值(“&”、“”)替换它们,只是我不知道正则表达式可以做到这一点。
这是我的尝试:
创建一个包含匹配项并引用替换值的对象:
var specialChars = {
" " : " ",
"&" : "&",
">" : ">",
"&lt;" : "<"
}
然后,我要匹配我的字符串
var stringToMatch = "This string has special chars &amp; and &nbsp;"
我试过类似的东西
stringToMatch.replace(/(&nbsp;|&)/g,specialChars["$1"]);
但它不起作用。我真的不明白如何捕获特殊标签并替换它。非常感谢任何帮助。
最佳答案
我认为您可以在稍微不同的主题 (Efficiently replace all accented characters in a string?) 上使用问题中的函数。
Jason Bunting 的回答有一些不错的想法 + 必要的解释,这是他的解决方案,经过一些修改可以帮助您入门(如果您觉得这有帮助,请也赞成他的原始答案,因为这是他的代码,本质上)。
var replaceHtmlEntites = (function() {
var translate_re = /&(nbsp|amp|quot|lt|gt);/g,
translate = {
'nbsp': String.fromCharCode(160),
'amp' : '&',
'quot': '"',
'lt' : '<',
'gt' : '>'
},
translator = function($0, $1) {
return translate[$1];
};
return function(s) {
return s.replace(translate_re, translator);
};
})();
可调用为
var stringToMatch = "This string has special chars & and &nbsp;";
var stringOutput = replaceHtmlEntites(stringToMatch);
编号的实体更容易,您可以使用一点数学和 String.fromCharCode()
更通用地替换它们.
另一种更简单的可能性是这样的(适用于任何浏览器)
function replaceHtmlEntites(string) {
var div = document.createElement("div");
div.innerHTML = string;
return div.textContent || div.innerText;
}
replaceHtmlEntites("This string has special chars < & >");
// -> "This string has special chars < & >"
关于javascript正则表达式替换html字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1229518/