开发者

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,


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜