regex替换在IE中不工作
regex replace not working in IE
好了,我用下面的答案和评论中改进的代码更新了这个问题,更类似于实际项目。但它仍然不能在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/
相关文章:
- 为什么这在IE中的工作方式与在Firefox中不同
- 点击选择Div不在IE上工作
- 如何编写在Chrome和IE中正常工作的JavaScript
- Target=_blank don'我不在mozilla和IE工作
- 如何隐藏空<span>在IE中使用javascript.(注意,在其他浏览器中工作正常)
- 读取在具有IE的工作程序中生成的对象URL
- Json到CSV下载,可以在chrome中工作,但不能在IE浏览器中工作
- jQUery Code没有'我不在IE工作
- 为什么这个书签脚本是't在IE工作
- 类构造函数super()没有'我不在IE工作
- JavaScript onclick在IE 9中工作两次,然后停止
- HTML5视频无法在chrome上工作,在服务器上托管后的IE,mov文件中的视频(quicktime格式)
- JSSOR转盘滑块在IE中不工作
- Iframe加载调整大小在Chrome中工作,但不能在IE或Firefox中工作
- onmousemove=null不会'我不在IE工作
- Javascript/AAJAX在Opera中不起作用,在FF/IE/Chrome中完美工作
- execCommand('另存为',true,'data.csv');不在IE工作
- 我的剧本赢了'不能在IE中工作(甚至9)?修改复制文本的简单javascript
- 纯Javascript: onClick切换行/图像:Firefox/Chrome -工作:IE -不工作
- jQuery菜单不工作ie(文档模式:怪癖)