宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

先看一道JavaScript题目,据说是国内某知名互联网企业的JavaScript笔试题,如果对正则的全局匹配模式不了解的话可能会对下面的输出结果感到疑惑。
[php]
var str = "123#abc";
var re = /abc/ig;
console.logre.teststr)); //输出ture
console.logre.teststr)); //输出false
console.logre.teststr)); //输出ture
console.logre.teststr)); //输出false
[/php]

在创建正则表达式对象时如果使用了“g”标识符或者设置它了的global属性值为ture时,那么新创建的正则表达式对象将使用模式对要将要匹配的字 符串进行全局匹配。在全局匹配模式下可以对指定要查找的字符串执行多次匹配。每次匹配使用当前正则对象的lastIndex属性的值作为在目标字符串中开 始查找的起始位置。lastIndex属性的初始值为0,找到匹配的项后lastIndex的值被重置为匹配内容的下一个字符在字符串中的位置索引,用来 标识下次执行匹配时开始查找的位置。如果找不到匹配的项lastIndex的值会被设置为0。当没有设置正则对象的全局匹配标志时lastIndex属性的值始终为0,每次执行匹配仅查找字符串中第一个匹配的项。可以通下面的代码来查看在执行匹配相应的lastIndex 属性的值。

[php]
var str = "123#abc";
var re = /abc/ig;
console.logre.teststr)); //输出ture
console.logre.lastIndex); //输出7
console.logre.teststr)); //输出false
console.logre.lastIndex); //输出0
console.logre.teststr)); //输出ture
console.logre.lastIndex); //输出7
console.logre.teststr)); //输出false
console.logre.lastIndex); //输出0
[/php]

这个时候可以在其中添加一条语句, 人工将位置归零, 防止这个 “错误” 的发生:
[php]
var re = /^\w$/g;
re.test’a’); //返回true
re.lastIndex = 0; //归零搜索的位置
re.test’b’); //返回true
[/php]
或者我们可以更简单地直接将g去掉:
[php]
var re = /^\w$/;
re.test’a’); //返回true
re.test’b’); //返回true
[/php]

转自:https://blog.csdn.net/leolu007/article/details/8576490