Introduction
Check whether a batch of mobile phone numbers meet the required format, and use regular verification to find invalid. I searched for the next information and found a place I didn't notice before.
problem
Here is the problem to reproduce:
const arr=['18311112222','18344445555','2857898098']
const reg = /^1[3-9]\d{9}$/g;
const result = arr.find(ele => !reg.test(ele));
console.info({result});
// {result: "18344445555"}
According to the above regularity, the second number meets the requirements, but false
is returned. I checked the data and found:
If the regular expression sets the global flagg
, the execution oftest()
will change the properties oflastIndex
Execute thetest()
method continuously, and the subsequent execution will start to match the stringlastIndex
Verify it:
const arr=['18311112222','18344445555','2857898098']
const reg = /^1[3-9]\d{9}$/g;
const result = arr.find(ele => {
const lastIndex = reg.lastIndex;
console.info({lastIndex});
return !reg.test(ele);
});
// {lastIndex: 0}
// {lastIndex: 11}
Solution
method 1
Remove the global flag g
, and think again that there is no need to use global matching in this scenario.
Method 2
Use String.prototype.search() .
const arr=['18311112222','18344445555','2857898098']
const reg = /^1[3-9]\d{9}$/g;
const result = arr.find(ele => ele.search(reg) === -1);
Method 3
Every time the loop matches, redeclare a regular.
const arr=['18311112222','18344445555','2857898098']
const result = arr.find(ele => {
const reg = /^1[3-9]\d{9}$/g;
return !reg.test(ele);
});
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。