IE8无法识别我的正则表达式 [英] IE8 is not recognizing my regular expression

查看:575
本文介绍了IE8无法识别我的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析AJAX响应并获取body标签的id。不过,我不能通过jQuery做到这一点,因为jQuery无法模拟body标签的DOM响应。

I'm trying to parse an AJAX response and get the id of the body tag. I can't do this via jQuery, though, because jQuery can't emulate a DOM response for a body tag.

我把它分成了很多行来尝试并隔离错误。这适用于现代浏览器,但它在IE8中失败。

I've split this into many lines to try and isolate the error. This works in modern browsers, but it's failing in IE8.

var bodyIDregex = new RegExp(/<body[^>]*id=["'](.*?)["']>/gi),
matched = html.match(bodyIDregex),
bodyID = bodyIDregex.exec(matched[0]);
bodyID = bodyID[1];

我已经确认变量html的值是预期的。

I have confirmed that the value of the variable html is as expected.

任何帮助?

谢谢!

推荐答案

你应该将字符串传递给regexen的构造函数,使用正则表达式文字语法,但不能同时使用两者。

You should either pass a string to the constructor for regexen, or use the regex literal syntax, but not both.

var bodyIDregex = /<body[^>]*id=["'](.*?)["']>/gi

var bodyIDregex = new RegExp("<body[^>]*id=[\"'](.*?)[\"']>","gi")

更新:

正如您在答案中正确指出的那样,问题是源于正则表达式搜索从前一个匹配中的最后一个字符的位置继续的事实。解决此问题的一种方法是重置 lastIndex ,但在这种情况下,这不是必需的,因为您只需要匹配字符串一次:

As you have correctly identified in your answer, the problem stems from the fact that the regex search continues from the position of the last character in the previous match. One way to correct this is to reset lastIndex, but in this case this is not required, since you only need to match against the string once:

var bodyIDregex = /<body[^>]*id=["'](.*?)["']>/gi,
    bodyID = bodyIDregex.exec(html);

//bodyID is now the array, ["<body id="test">asdf</body>", "test"]

alert(bodyID[1]);
//alerts the captured group, "test"

这篇关于IE8无法识别我的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆