Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE Javascript String.Match issue

The following javascript code concatenates the matches found by a regular expression. The regular expression should find any word or set of quoted words. It seems to work perfectly in FireFox and Chrome, but its not working correctly in IE (i have only tested it on IE8).

var searchString = '';
var notString = 'dog cat "pirate ship"';
var matches = notString.match(/(\w+|"[^"]+")/ig);
for (i in matches) {
    searchString += " NOT " + matches[i];

}
alert(searchString );

The correct output should be:

NOT dog NOT cat NOT "pirate ship"

but in IE8 im getting:

NOT dog cat "pirate ship" NOT dog NOT cat NOT "pirate ship" NOT 8 NOT 21

Any suggestions on how to make this cross browser compatible.

Many thanks,

like image 341
Benjamin Ortuzar Avatar asked Apr 18 '26 10:04

Benjamin Ortuzar


1 Answers

The problem is your use of the for...in statement. A for...in statement will iterate over all enumerable properties of an object, they're not really suitable for iterating over array elements -- in this case it is iterating over the following properties:

matches.input
matches.0
matches.1
matches.2
matches.index
matches.lastIndex

See also http://msdn.microsoft.com/en-us/library/7df7sf4x(VS.85).aspx:

The array returned by the match method has three properties, input, index and lastIndex. The input property contains the entire searched string. The index property contains the position of the matched substring within the complete searched string. The lastIndex property contains the position following the last character in the last match.

Use a proper for statement instead:

for (var i = 0; i < matches.length; i++)
    searchString += " NOT " + matches[i];
like image 121
Andy E Avatar answered Apr 21 '26 01:04

Andy E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!