1

I am trying to learn how to break up this string:

var str = 'red','blue','gree'

I have this working code:

var clean = str.replace(/\'/g, "");
var elements = clean.split(',');

which produces array ["red","blue","green"] which is what i want however. id like to learn how to do this using regex.exec() method.

here is what i got:

var patt = /([^']+)/g;
var elem= patt.exec(str); 

but this returns array ["red","red"]

any ideas?

4

1 回答 1

2

使用exec, 要获得多个匹配项,您需要循环运行它...

var str = "'red','blue','gree'"; // making a guess here

var patt = /([^']+)/g;
var match;

       //   v----yes, an assignment
while(match = patt.exec(str)) {
    console.log(match[1]);
}

演示:http: //jsfiddle.net/D62D4/

全局正则表达式将最后一次匹配结束后的索引存储在自身上,并从该点开始执行下一个查询。

这一直持续到没有匹配项,此时索引设置回0.

.lastIndex您可以使用该属性在正则表达式上观察和修改此索引。

于 2012-06-22T23:52:56.630 回答