1

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 flag g , the execution of test() will change the properties of lastIndex Execute the test() method continuously, and the subsequent execution will start to match the string lastIndex

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);
});

Reference


XXHolic
363 声望1.1k 粉丝

[链接]