Unexpected regex behavior with /null/g.test('null null ')

var re = /null/g;

re.test('null null');
//> true

re.test('null null');
//> true

re.test('null null');
//> false

WHAT!?!?

I tried testing in Chrome, Firefox, Safari. A regular expression is used with the RegExp constructor, but to no avail.

Why is this happening?

JS Bin with an additional demo

+4
source share
2 answers

Global regular expressions (those that use the flag g) are special. If you call them on the same line multiple times, they look for consecutive matches. Since your test string contains exactly two matches for null, the third call RegExp#testreturns false(the third match in the string cannot be found).

, g :

var re = /null/

console.log(re.test('null null')) //=> true
console.log(re.test('null null')) //=> true
console.log(re.test('null null')) //=> true
+4

, , . "g" . .

0

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


All Articles