Kato
Kato

Reputation: 40582

regex match() works in FF/Chrome but not IE 8

I have the following jQuery call, which returns a match in FF/Chrome, but returns null in IE 8.

Here's the fiddle if you'd like to try it for yourself.

And here's the insoluble, unpliable, wayward code:

var m = $('#somediv').text().match(/\d+-(\d+)\sof\s(\d+)/);

EDIT: Thanks to Rob W. I've narrowed this a bit; the following works, so it's specifically the " of " or "\sof\s" that fails. Fork the fiddle and try a few for yourself :(

var m = $('#somediv').text().match(/\d+\D(\d+)\D+(\d+)/);

Upvotes: 3

Views: 5787

Answers (3)

gilly3
gilly3

Reputation: 91497

Use this RegExp:

/\d+-(\d+)\xa0of+\xa0(\d+)/

http://jsfiddle.net/gilly3/KNbpN/

Sadly, it seems, IE8 doesn't recognize non-breaking spaces as a white-space (\s) match.

Upvotes: 2

John Flatness
John Flatness

Reputation: 33769

Building on Rob W's answer, which picks up on the problem that replace doesn't replace globally by default, the other thing that's off here is the actual text you're searching for. Rob W also points out that since you're getting the text with jQuery's text(), the   entities have been decoded to actual, factual non-breaking space characters.

  is a HTML entity, specifying it as an argument to replace isn't going to actually interpret it as a non-breaking space, it's just going to look for the actual text   in the subject string.

Specifying the Unicode codepoint for the non-breaking space (00A0) in the search regex worked for me in IE 8 and IE 7 compatibility mode:

var m = t.replace(/\u00a0/g, ' ').match(/\d+-(\d+)\sof\s(\d+)/);

Things work correctly in IE 9 because it, like other browsers, includes non-breaking spaces in \s. Older versions of IE don't, and that's the only reason the replacement would be necessary.

Upvotes: 3

Rob W
Rob W

Reputation: 349012

Your code would only replace the first occurence of  . However, since you're getting the text using .text(), the replace function should not be needed.

var m = t.replace(/ /g, ' ').match(/\d+-(\d+)\sof\s(\d+)/);

If your issue is not solved using the previous line, use alert(t) to check whether the input is as expected.

Upvotes: 2

Related Questions