我正在使用JavaScript来设置输入的值,其中包含可能包含HTML特定字符的文本& 等等.所以,我试图找到一个匹配这些值的正则表达式并用适当的值替换它们("&" ,"")分别只有我无法弄清楚正则表达式才能做到这一点.
这是我的尝试:
创建一个包含匹配项的对象和对替换值的引用:
var specialChars = {
" " : " ",
"&" : "&",
">" : ">",
"&lt;" : "<"
}
Run Code Online (Sandbox Code Playgroud)
然后,我想匹配我的字符串
var stringToMatch = "This string has special chars &amp; and &nbsp;"
Run Code Online (Sandbox Code Playgroud)
我试过类似的东西
stringToMatch.replace(/(&nbsp;|&)/g,specialChars["$1"]);
Run Code Online (Sandbox Code Playgroud)
但它不起作用.我真的不明白如何捕获特殊标签并替换它.任何帮助是极大的赞赏.
Tom*_*lak 17
我想你可以在一个稍微不同的主题上使用问题中的函数(有效地替换字符串中的所有重音字符?).
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);
};
})();
Run Code Online (Sandbox Code Playgroud)
可赎回的
var stringToMatch = "This string has special chars & and &nbsp;";
var stringOutput = replaceHtmlEntites(stringToMatch);
Run Code Online (Sandbox Code Playgroud)
编号的内容甚至更容易,您可以使用一些数学和数字来更换它们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 < & >"
Run Code Online (Sandbox Code Playgroud)