primers

Check whether a batch of mobile phone numbers are in line with the required format, and check with the regular cycle, found invalid. I looked it up and found something I hadn’t noticed before.

The problem

Here are the recurring problems:

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"}
Copy the code

Select * from ‘regex’ where ‘false’ is returned

If the global flag G is set to the regular expression, the execution of test() changes the lastIndex property of the regular expression. Execute the test() method consecutively, and subsequent executions will match the string starting at lastIndex.

Verify:

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}
Copy the code

The solution

Method 1

Remove the global flag G and think again that there is no need for global matching in this scenario.

Method 2

Using String. The prototype. The search ().

const arr=['18311112222'.'18344445555'.'2857898098']
const reg = /^1[3-9]\d{9}$/g;
const result = arr.find(ele= > ele.search(reg) === -1);
Copy the code

Methods 3

Each time the loop matches, a re is redeclared.

const arr=['18311112222'.'18344445555'.'2857898098']
const result = arr.find(ele= > {
  const reg = /^1[3-9]\d{9}$/g;
  return! reg.test(ele); });Copy the code

The resources

more

Recently, the word “paradise chase” has been floating in my mind, so I went to search for it. As soon as I saw that the cover seemed to be a work of mecha class, I felt not interested. But in order to solve the doubts in my heart, I went to have a look.

Turns out there are mecha, but the best mecha fights come at the end, and there aren’t many of them. Most of the stories discussed the virtual world, AI and human beings from different angles, which I personally felt was quite interesting.