代码之家  ›  专栏  ›  技术社区  ›  brad

javascript regex替换HTML字符

  •  5
  • brad  · 技术社区  · 15 年前

    我正在使用javascript设置输入值,其中的文本可能包含特定于HTML的字符,例如 &   等等。所以,我试图找到一个与这些值匹配的regex,并分别用适当的值(“&”,“”)替换它们,但我无法找到要执行此操作的regex。

    这是我的尝试:

    生成包含匹配项和替换值引用的对象:

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

    然后,我想匹配我的线

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

    我试过类似的东西

    stringToMatch.replace(/(&amp;nbsp;|&amp;)/g,specialChars["$1"]);
    

    但它不起作用。我真的不知道如何捕获这个特殊的标签并替换它。非常感谢您的帮助。

    5 回复  |  直到 6 年前
        1
  •  16
  •   Community CDub    8 年前

    我想你可以在稍微不同的主题上使用问题的函数( Efficiently replace all accented characters in a string? )

    杰森·邦廷的回答有一些好主意+必要的解释,这是他的解决方案,有一些修改,让你开始。( 如果你觉得这有帮助的话,把他的原始答案也投赞成票,因为这是他的代码,本质上 )

    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 < & >"
    
        2
  •  2
  •   BYK    15 年前

    另一种方法是创建DIV对象

    var tmp = document.createElement("div");
    

    然后将文本分配给它的innerhtml

    tmp.innerHTML = mySpecialString;
    

    最后读取元素的文本内容

    var output = tmp.textContent || tmp.innerText //for IE compatibility
    

    就这样……

        3
  •  1
  •   Umber Ferrule Gokhan Tank    13 年前

    您可以使用基于函数的替换来执行您想要执行的操作:

    var myString = '&'+'nbsp;&'+'nbsp;&tab;&copy;';
    myString.replace(/&\w+?;/g, function( e ) {
        switch(e) {
            case '&nbsp;': 
                return ' ';
            case '&tab;': 
                return '\t';
            case '&copy;': 
                return String.fromCharCode(169);
            default: 
                return e;
        }
    });
    

    不过,我确实敦促你考虑一下你的处境。如果在文本值中接收和复制以及其他HTML实体,是否确实要替换它们?之后你应该转换它们吗?

    只是要记住一些事情。

    干杯!

        4
  •  0
  •   Kyle Baker    7 年前

    不使用痛苦的开关/案例陈述的现代变体:

    const toEscape = `<code> 'x' & "y" </code> <\code>`
    
    toEscape.replace(
      /[&"'<>]/g,
      (char) => ({
          "&": '&amp;',
          "\"": '&quot;',
          "'": '&#39;',
          "<": '&lt;',
          ">": '&gt;',
        })[char]
    )
    

    或者,因为这真的应该变成一个函数:

    const encodeHTML = function(str) {
        const charsToEncode = /[&"'<>]/g
        const encodeTo = {
          "&": '&amp;',
          "\"": '&quot;',
          "'": '&#39;',
          "<": '&lt;',
          ">": '&gt;',
        }
        return str.replace(charsToEncode, char => encodeTo[char])
    }
    

    (此字符列表是根据 list of XML-escape-char-codes available on wikipedia )

        5
  •  0
  •   Alberto S.    6 年前

    替换任何HTML标记和HTML特殊字符的更好方法是用regex替换它们

    str.replace(/<[^>]*>/g, '').replace(/[^\w\s]/gi, '')