我正在使用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)
但它不起作用.我真的不明白如何捕获特殊标签并替换它.任何帮助是极大的赞赏.