javascript - 关于正则表达式exec方法全局模式匹配下有个问题
PHP中文网
PHP中文网 2017-04-10 17:09:08
0
2
406

var str="1 plus 2 equal 3";
x=str.match(/\d+/g);

y=/\d+/g.exec(str);
document.write(x+"<br/>");//1,2,3
document.write(y+"<br/>");//1
y=/\d+/g.exec(str);
document.write(y+"<br/>");//1??应该是2??
y=/\d+/g.exec(str);
document.write(y+"<br/>");//1??应该是3啊??

PHP中文网
PHP中文网

认证0级讲师

reply all(2)
巴扎黑
var str="1 plus 2 equal 3";
rex = /\d+/g;
y=rex.exec(str);  // 1
console.log(y);
console.log(rex.lastIndex);
y=rex.exec(str);  // 2
console.log(y);
console.log(rex.lastIndex);
y=rex.exec(str);  // 3
console.log(y);
console.log(rex.lastIndex);

要这样写,你那种写法每次都是一个新的RegExp对象,所以三次调用都是取的第一个匹配结果

左手右手慢动作
var str="1 plus 2 equal 3";
x=str.match(/\d+/g);
console.log(x);//1,2,3
y=/\d+/g.exec(str);
console.log(y);//1
y=/\d+/g.exec(str);
console.log(y);//1??应该是2??
y=/\d+/g.exec(str);
console.log(y);//1??应该是3啊??

每次执行exec方法是正则表达式都是一个新的和之前的不同,所以它们之间是无关的,匹配的lastIndex也不会传递下去
要想输出其期望的要这样修改:

var str="1 plus 2 equal 3";
x=str.match(/\d+/g);
console.log(x);//1,2,3
var myRegExp=/\d+/g;
y= myRegExp.exec(str);
console.log(y);//1
y= myRegExp.exec(str);
console.log(y);//2
y= myRegExp.exec(str);
console.log(y);//3
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template