What part of this RegEx is causing it to find no m

2019-07-15 10:25发布

问题:

I've got a regex that looks for a <span> with the class name foobar. It works in IE9, Chrome and Firefox. It's failing in IE7 and IE8. Can anyone tell me why?

new RegExp( /(\s*?)<span\b(?:.*?)(?:class=(?:'|"|.*?\s)?foobar(?:\s|\3))(?:.*?)(?:\/)?>(.+?)<\/span>(\s*?)/g )

回答1:

If you're applying the regex against html you got from getElementById().innerHTML or jQuery .html(), IE will uppercase the HTML tags which could be the problem. If you make the regex case-insensitive - that is, change the modifier /g to /gi at the end - does that fix it ?

It seems like you're also mixing the regex literal and RegExp object syntax, you can do it with just the regex literal instead.

var regex = /(\s*?)<span\b(?:.*?)(?:class=(?:'|"|.*?\s)?foobar(?:\s|\3))(?:.*?)(?:\/)?>(.+?)<\/span>(\s*?)/gi;