views:

25

answers:

2

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,

+1  A: 

What happens when you do:

for (var i = 0; i < matches.length; ++i) { /* ... */ }

Using the "in" form of "for" loops on array instances is mighty risky.

edit check out AndyE's answer, in particular the thing about the "input" property.

Pointy
+1  A: 

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];
Andy E