为什么`pattern.test(name)`在连续调用时产生相反的结果 [英] Why `pattern.test(name)` opposite results on consecutive calls

查看:809
本文介绍了为什么`pattern.test(name)`在连续调用时产生相反的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码首先返回true,然后返回false

Why is this code returning first true, then false

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

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

演示:小提琴

推荐答案

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

g is for repeating searches. It changes the regular expression object into an iterator. If you want to use the test function to check your string is valid according to your pattern, remove this modifier :

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

测试函数,与<$相反c $ c> replace 或 match 不会消耗整个迭代,这使得它处于坏状态。使用 test 函数时,您可能永远不会使用此修饰符。

The test function, contrary to replace or match doesn't consume the whole iteration, which lets it in a "bad" state. You should probably never use this modifier when using the test function.

这篇关于为什么`pattern.test(name)`在连续调用时产生相反的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆