最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - IE Javascript String.Match issue - Stack Overflow

programmeradmin2浏览0评论

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 patible.

Many thanks,

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 patible.

Many thanks,

Share Improve this question asked Apr 13, 2010 at 15:57 Benjamin OrtuzarBenjamin Ortuzar 7,8316 gold badges44 silver badges46 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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./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 plete 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)

  1. 暂无评论