Home > Web Front-end > JS Tutorial > Why Does a Global Regexp's `test()` Method Return Unexpected Results?

Why Does a Global Regexp's `test()` Method Return Unexpected Results?

Patricia Arquette
Release: 2024-12-21 12:26:10
Original
721 people have browsed it

Why Does a Global Regexp's `test()` Method Return Unexpected Results?

Wrong Results from Regexp with Global Flag

In the provided code, the regular expression new RegExp(query, 'gi') is used with both the g (global) and i (case insensitive) flags. However, the result is unexpected: [true, false].

Understanding the Global Flag

The g flag in a RegExp object controls the behavior of the test() method. When set, test() searches for the pattern in the string repeatedly, starting from where the previous match ended. This is known as "stickiness."

Incorrect Result Explanation

In the example, the first call to re.test('Foo Bar') finds the match "Foo B." Since the g flag is set, lastIndex is updated to the position after "Foo B." This means the subsequent call to re.test('Foo Bar') starts searching from the position after "Foo B." No match is found, leading to the false result.

Example with Sticky Flag

Consider the following code:

var reg = /^a$/g;
for(i = 0; i++ < 10;)
   console.log(reg.test("a"));
Copy after login

This code prints "true" 10 times. Since reg has the g flag, it sticks to the last match, repeatedly testing "a" from the position after the previous match until the end of the string.

Solution

To fix the original code, reset re.lastIndex to 0 before each test() call:

var query = 'Foo B';
var re = new RegExp(query, 'gi');
result.push(re.test('Foo Bar'));
re.lastIndex = 0;
result.push(re.test('Foo Bar'));
Copy after login

This ensures that the search starts from the beginning of the string for each test() call, yielding the correct result of [true, true].

The above is the detailed content of Why Does a Global Regexp's `test()` Method Return Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template