📜 ⬆️ ⬇️

Regular trap

Suppose we want to check with a regular expression that there is at least one digit in the string. Write the code:

<script>

var digits = /([0-9])+/g;

function has_digit(s) { return digits.test(s); }

</script>


This code is incorrect .
Why is it obvious to you? If not - welcome under the cat!
')


By the way, see for yourself:

<script>

document.write(has_digit("abc0xyz") + ' ' + has_digit("abc0xyz"));

</script>


We get:

true false

And should, of course:

true true

The has_digit () function regularly gives the wrong answer. Referring to the worldwide intelligence of the web.

http://javascript.ru

To simply find out if the string matches the regexp regular expression, use regexp.test (string).

Two, the answer is incorrect.

http://www.regular-expressions.info

The test () function of the RegExp object is a shortcut to exec ()! = Null. It depends on whether or not it’s true.

Two, the answer is incorrect.

Etc.

Long story short. We read the standard.

RegExp.prototype.test (string)
Equivalent to the expression RegExp.prototype.exec (string)! = Null.


So the matter is in the magic bubbles of the RegExp.prototype.exec function (string).

Its algorithm is as follows: in the presence of the g flag in a regular expression, the match search starts with the lastIndex property (this is a regular expression property). Initially, it is zero, but after a successful search it is updated by the position to search for the next match.

Here is the solution. In global regular expressions, the test () function does not necessarily look for matches from the beginning of the string .

The problem is compounded by the fact that the regular expression is usually used in the form:

/([0-9])+/g.test("abc")


This code does not cause problems. Why? It is not difficult to see that each time this code is executed, a new regular expression is created and the search comes from the zero position.

Of course, I was not the first to step on this rake.

http://stackoverflow.com

It is surprising that most of the network resources on JavaScript were useless.

I hope someone will save this information precious time ...

UDP

Yes, the global flag is not needed in this case.

Once again - if you understood what was wrong - you could not go under the cut :-)

Source: https://habr.com/ru/post/112824/


All Articles