如何用正则表达式的 lastIndex 找到匹配字符串的最后一个索引?

2026-03-30 08:130阅读0评论SEO教程
  • 内容介绍
  • 相关推荐

本文共计196个文字,预计阅读时间需要1分钟。

如何用正则表达式的 lastIndex 找到匹配字符串的最后一个索引?

下面是简化后的代码内容,不包含数数,不超过100字:

看下面这段代码:function test(s){ var reg=/./g; console.log(reg.exec(s)); console.log(reg.lastIndex); var reg=/./g; console.log(reg.exec(s)); console.log(reg.lastIndex);}test(abcd);test(efgh);我输出的lastIndex值

如何用正则表达式的 lastIndex 找到匹配字符串的最后一个索引?

看下面这段代码:
function test(s){
var reg = /./g;
console.log(reg.exec(s));
console.log(reg.lastIndex);
var reg = /./g;
console.log(reg.exec(s));
console.log(reg.lastIndex);
}
test("abcd");
test("efgh");
我以为输出的lastIndex的值应该都是1,但是实际上的输出如下:
a
1
a
1
f
2
f
2
感觉就像是在第二次调用test的时候第2行和第6行并没有产生新的正则表达式,其之前的属性lastIndex还保留着(lastIndex=1)。
阅读全文

本文共计196个文字,预计阅读时间需要1分钟。

如何用正则表达式的 lastIndex 找到匹配字符串的最后一个索引?

下面是简化后的代码内容,不包含数数,不超过100字:

看下面这段代码:function test(s){ var reg=/./g; console.log(reg.exec(s)); console.log(reg.lastIndex); var reg=/./g; console.log(reg.exec(s)); console.log(reg.lastIndex);}test(abcd);test(efgh);我输出的lastIndex值

如何用正则表达式的 lastIndex 找到匹配字符串的最后一个索引?

看下面这段代码:
function test(s){
var reg = /./g;
console.log(reg.exec(s));
console.log(reg.lastIndex);
var reg = /./g;
console.log(reg.exec(s));
console.log(reg.lastIndex);
}
test("abcd");
test("efgh");
我以为输出的lastIndex的值应该都是1,但是实际上的输出如下:
a
1
a
1
f
2
f
2
感觉就像是在第二次调用test的时候第2行和第6行并没有产生新的正则表达式,其之前的属性lastIndex还保留着(lastIndex=1)。
阅读全文