regex替换在IE中不工作

regex replace not working in IE

本文关键字:工作 IE 替换 regex      更新时间:2023-09-26

好了,我用下面的答案和评论中改进的代码更新了这个问题,更类似于实际项目。但它仍然不能在IE8中工作。小提琴在

<ul id="definitions">
    <li id="defid63">keyword1<input type="hidden" value="63" /></li>
    <li id="defid61">keyword2<input type="hidden" value="61" /></li>
    <li id="defid62">Keyword3<input type="hidden" value="62" /></li>
</ul>
<div id="html">Lorem ipsum keyword1 dolor keyword2 sit keyword3 amet, consectetur adipisicing elit, sed do eiusmod tempor</div>

我有一个关键字列表(ul > li),有一个字符串与一些文本。我想用<a>标签包装每个关键字的出现。我的代码在firefox和chrome中工作良好,但IE(8)不匹配正则表达式。

jQuery(function($) {
    // created by Gracenotes
    // http://goo.gl/MTkcY
    RegExp.quote = function(str) {
        return str.replace(/([.?*+^$[']''(){}-])/g, "''$1");
    };
    var $node = $('#html'),
        // the dom element
        html = $node.html(); // the text we'll manipulate
    $('#definitions li').each(function() {
        var defid = $(this).find('input').val(),
            deftext = $(this).html().split("<input")[0],
            //the keyword
            //pattern = eval('/''b('+RegExp.quote(deftext)+')''b/gi');
            pattern = new RegExp('''b(' + RegExp.quote(deftext) + ')''b', 'gi');
        html = html.replace(pattern, '<a href="#id=' + defid + '">$1</a>');
    });
    // replace the dom content with our updated text
    $node.html(html);
});

应该可以:

var pattern = new RegExp(''b('+def+')'b','gi');

将变量传递给javascript中的regexp

此功能适用于ie8;在这个小提琴上测试一下。

我是这样做的:

  • 用RegExp
  • 替换eval()
  • 在使用regex
  • 之前转义了引用文本
  • 伪造了id,因为你没有提供代码

代码

jQuery(function($) {
    // created by Gracenotes
    // http://goo.gl/MTkcY
    RegExp.quote = function(str) {
       return str.replace(/([.?*+^$[']''(){}-])/g, "''$1");
    };
    var $node = $('#html'),   // the dom element
        html  = $node.html(); // the text we'll manipulate
    $('#definitions li').each(function() {
        var $this   = $(this),
            //I didn't know where defid came from
            //so I just added it as id attribute
            defid   = $this.attr('id'), 
            deftext = $(this).text(), //the keyword
            pattern = new RegExp('''b(' + RegExp.quote(deftext) + ')''b', 'gi');
        html = html.replace(pattern, '<a href="#id=' + defid + '">$1</a>');
    });
    // replace the dom content with our updated text
    $node.html(html);
});

好吧,实际的问题在我的问题的第一个版本中没有提供的代码中。我使用了代码deftext = $(this).html().split("<input")[0],这在IE8中不起作用,因为IE将标签更改为大写字符。像FF和Chrome这样的浏览器不会这样做。因此,使用eval()生成表达式确实可以工作,并且不是真正的问题:演示这里http://jsfiddle.net/zluiten/79rhW/