Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

javascript - IE8 is not recognizing my regular expression

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.

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];

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

Any help?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

or

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

Update:

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...