2

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 )
buley
  • 28,032
  • 17
  • 85
  • 106
  • 1
    Why are you wrapping a regex literal with the regex constructor? Lose the `new RegExp(` and `)`, they're not needed. – Andy E Nov 09 '11 at 16:25

1 Answers1

3

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;
Michael Low
  • 24,276
  • 16
  • 82
  • 119
  • 2
    +1 — IE 9 changed `innerHTML` and `outerHTML` to return HTML with lower-case node names, so I think you've hit the nail on the head. – Andy E Nov 09 '11 at 16:28
  • Yesssirree. Great get. Many thanks. I often use the RegEx constructor when I don't know the value of "foobar" in advance but in this case I do and your solution is a simplification. Thank you. – buley Nov 09 '11 at 16:52