RegEx not working in IE8

2019-08-09 03:34发布

问题:

OK, after searching high and low both here and on Google I have to bite the bullet and ask a new question here regarding RegEx in IE8.

I have the following code:

var output = input.replace(/^\S+(\s| )+/, '');

Its purpose is to remove currency names from amounts, so "kr 12 345,00" becomes "12 345,00" and "NOK 12 345,00" becomes "12 345,00" and so on.

This works fine everywhere except in Internet Explorer versions 8 or below, where it leaves the input unchanged.

Initially I was using the new RegExp() way of doing it, but changed it to the regular expression literal to see if there was a difference between how IE handled those two variations - which, thankfully, there wasn't :)

I have also tried with just the \s and with just the   but that didn't make a difference.

The really weird thing is that when running the above regex with "kr 12 345,00" as the input on W3 School's "Try It Yourself" page in IE 8 it works fine! (also when the first space is substituted with  )

So to reiterate: The place I'm seeing this issue is when using the regex in my Javascript code, which resides in an AngularJS filter function (I'm defining a filter), and the filter is returning the original input in IE8 (which is also seen with console.log() in IE8). Someone else tested it in IE9 for me, and reported that it worked fine there - and I have tested in Chrome as well. The only browsers in which I've encountered this issue are IE8 and IE7.

What on earth is happening here?

回答1:

Try

var output = input.replace(/^\S+([\s\xA0]| )+/, '');

According to here, "in IE8... \s (which should include all white space) doesn’t include non-breaking space".

Or better, just use

var output = input.replace( /^\D+/, '' );

where \D is any non-digit character.



回答2:

Firstly as you're checking for   I guess you're getting this value from the html (using el.innerHTML or $(el).html(). A better method, which converts all non-breaking whitespace into ' ' is to use el.textContent or $(el).text() (which also covers you for instances where e.g. the currency name is wrapped in a span (which possibly would have numbers in its attributes))

Then the following regex to replace all non digits at the start of the string

var output = input.replace(/^[^\d]+/, '');