Javascript 为什么`pattern.test(name)`连续调用的结果相反

Javascript 为什么`pattern.test(name)`连续调用的结果相反,javascript,regex,Javascript,Regex,为什么这段代码先返回true,然后返回false var pattern = new RegExp("mstea", 'gi'), name = "Amanda Olmstead"; console.log('1', pattern.test(name)); console.log('1', pattern.test(name)); 演示:g用于重复搜索。它将正则表达式对象更改为迭代器。如果要使用test函数根据模式检查字符串是否有效,请删除此修饰符: var pattern = new R

为什么这段代码先返回true,然后返回false

var pattern = new RegExp("mstea", 'gi'), name = "Amanda Olmstead";

console.log('1', pattern.test(name));
console.log('1', pattern.test(name));

演示:

g
用于重复搜索。它将正则表达式对象更改为迭代器。如果要使用
test
函数根据模式检查字符串是否有效,请删除此修饰符:

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";

replace
match
相反,
test
函数不会消耗整个迭代,从而使其处于“坏”状态。在使用
test
函数时,可能永远不应该使用此修饰符

因为您设置了
g
修饰符

为您的案例移除它

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";

您不希望将gi与pattern.test结合使用。g标志表示它跟踪您正在运行的位置,以便可以重用。因此,您应该使用:

var pattern = new RegExp("mstea", 'i'), name = "Amanda Olmstead";

console.log('1', pattern.test(name));
console.log('1', pattern.test(name));
此外,您还可以对regex使用/../[flags]语法,如下所示:

var pattern = /mstea/i;

这不是一个bug。

g
使它在第一次匹配后对子字符串执行下一次尝试的匹配。这就是为什么它在每次偶数尝试中返回false

First attempt: 
It is testing "Amanda Olmstead"

Second attempt:
It is testing "d" //match found in previous attempt (performs substring there)

Third attempt:
It is testing "Amanda Olmstead" again //no match found in previous attempt

... so on
各州的MDN页面:

如果正则表达式使用“g”标志,则可以使用exec 方法多次查找同一字符串中的连续匹配项。 执行此操作时,搜索从指定的str的子字符串开始 正则表达式的lastIndex属性

各州的MDN页面:

与exec(或与之结合使用)一样,test被多次调用 在同一个全局上,正则表达式实例将前进到 上一场比赛


它会在不同的
test()之间保留最后找到的索引的轨迹吗
calls@ArunPJohny我认为在测试函数中使用“g”标志是没有意义的。我在调试时遇到了这个问题,也许你可以回答这个问题too@ArunPJohny这似乎是同样的问题,是的。我让你回答。这是同样的问题,因为循环-只有交替的结果将显示