js使用正则时碰到的奇怪问题、、、

本文详细解析了正则表达式中全局匹配模式'g'的使用方式及其对lastIndex属性的影响,并提供了实例说明如何正确使用全局匹配避免潜在的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

var regExp = /^Sol[0-9]$/gi;
var isContained = regExp.test(value);
alert("regExp.test("+value+")="+regExp.test(value) + " isContained="+isContained);

 

最后的提示如下:

 


 

甚是不解、、、

 

后来在网上google一番、、、

 

给出如下解释:

RegExp中有一个全局变量lastIndex,它记录待匹配串中下次匹配开始时的字符位置。默认为0,如果匹配成功,则是上次匹配串的长度,如果没有匹配成功,也返回0.

该变量有正则表达式对象的exec和test方法改变,也可以由String对象的replace,match和split等方法来改变,这个需要注意。

 

Also
RegExp Object Properties | Regular Expression Syntax

Applies To: RegExp Object
Requirements
Version 3
Returns the character position where the next match begins in a searched string.

RegExp.lastIndex
The object associated with this property is always the global RegExp object.

Remarks
The lastIndex property is zero-based, that is, the index of the first character is zero. Its initial value is –1. Its value is modified whenever a successful match is made.

The lastIndex property is modified by the exec and test methods of the RegExp object, and the match, replace, and split methods of the String object.

The following rules apply to values of lastIndex:

If there is no match, lastIndex is set to -1.
If lastIndex is greater than the length of the string, test and exec fail and lastIndex is set to -1.
If lastIndex is equal to the length of the string, the regular expression matches if the pattern matches the empty string. Otherwise, the match fails and lastIndex is reset to -1.

 

因为在我的正则表达式中使用了全局匹配模式 "g" , 所以用完了之后 必须要重置lastIndex.

或者去掉全局匹配模式的参数 "g" , 这样儿就一致了、、、

O(∩_∩)O~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值