js 正则表达式的怪异
看例子吧
var reg = new RegExp("abc","gi"); console.log(reg.test("abc")); console.log(reg.test("abc")); console.log(reg.test("abc")); console.log(reg.test("abc")); console.log(reg.test("abc")); console.log(reg.test("abc")); console.log(reg.test("abc")); console.log(reg.test("abc"));
惊奇的发现打印结果不一样啊
解决办法有3种
1
var reg = new RegExp("abc","i"); console.log(!!reg.match("abcd")); console.log(!!reg.match("abcd")); console.log(!!reg.match("abcd")); console.log(!!reg.match("abcd")); console.log(!!reg.match("abcd")); console.log(!!reg.match("abcd")); console.log(!!reg.match("abcd")); console.log(!!reg.match("abcd"));
2
var reg = new RegExp("abc","gi"); reg.lastIndex=0;console.log(reg.test("abc")); reg.lastIndex=0;console.log(reg.test("abc")); reg.lastIndex=0;console.log(reg.test("abc")); reg.lastIndex=0;console.log(reg.test("abc")); reg.lastIndex=0;console.log(reg.test("abc")); reg.lastIndex=0;console.log(reg.test("abc")); reg.lastIndex=0;console.log(reg.test("abc")); reg.lastIndex=0;console.log(reg.test("abc"));
3
var reg = new RegExp("abc","gi"); var reg = new RegExp("abc","gi"); console.log(!!'abc'.match(reg)); console.log(!!'abc'.match(reg)); console.log(!!'abc'.match(reg)); console.log(!!'abc'.match(reg)); console.log(!!'abc'.match(reg)); console.log(!!'abc'.match(reg));
相关推荐
wangzhaotongalex 2020-10-20
wyq 2020-11-11
TLROJE 2020-10-26
风雨断肠人 2020-10-13
duanqingfeng 2020-09-29
rechanel 2020-11-16
cshanzhizi 2020-10-16
luofuIT成长记录 2020-09-22
phphub 2020-09-10
taomengxing 2020-09-07
MaggieRose 2020-08-19
flyingssky 2020-08-18
山水沐光 2020-08-18
jyj00 2020-08-15
AHuqihua 2020-08-09
山水沐光 2020-08-03