javascript正则表达式替换html字符

标签 javascript regex

我正在使用 JavaScript 来设置输入的值,其中文本可能包含 HTML 特定字符,例如 &   等。所以,我试图找到一个匹配这些值的正则表达式,并分别用适当的值(“&”、“”)替换它们,只是我不知道正则表达式可以做到这一点。

这是我的尝试:

创建一个包含匹配项并引用替换值的对象:

var specialChars = {
  " " : " ",
  "&"  : "&",
  ">"   : ">",
  "&amp;lt;"   : "<"
}

然后,我要匹配我的字符串

var stringToMatch = "This string has special chars &amp;amp; and &amp;nbsp;"

我试过类似的东西

stringToMatch.replace(/(&amp;nbsp;|&amp;)/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 &amp; and &amp;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 &lt; &amp; &gt;");
// -> "This string has special chars < & >"

关于javascript正则表达式替换html字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1229518/

相关文章:

javascript - 将鼠标悬停在数据表中的图标上时显示弹出窗口

javascript - 如何停止 qUnit 中的全局故障?

javascript - 使用 Handlebars 'each' 循环访问父级的属性

javascript - 使用 anchor 时在 Firefox 中重新加载页面?

javascript - 解释用于从 String 中删除 html 代码的正则表达式

regex - Perl/正则表达式 : how to find and replace between sets of every n characters

javascript - 在 nextjs 中是否有来自 'react-router-dom' 的 {useLocation} 的等价物

java - 正则表达式在 drools 5.3.0 中不起作用

ruby - gsub 数字和 +

python - 允许在我的正则表达式中使用转义序列