RegExp inconsistency between String.replace and RegExp.test()

RESOLVED INVALID

Status

()

Core
JavaScript Engine
RESOLVED INVALID
5 years ago
5 years ago

People

(Reporter: Nicolas FROIDURE, Unassigned)

Tracking

18 Branch
x86_64
Linux
Points:
---

Firefox Tracking Flags

(Not tracked)

Details

(Reporter)

Description

5 years ago
User Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17

Steps to reproduce:

Created a RegExp object, tested a string and did not match, but when using string.replace with the same RegExp object, the expression match.

https://gist.github.com/4692419


Actual results:

RegExp.test and String.replace behaves differently


Expected results:

I assume they should match equally on the same string

Updated

5 years ago
Assignee: nobody → general
Component: Untriaged → JavaScript Engine
Product: Firefox → Core
This is not a bug, but rather subtleties involving the lastIndex property of regular expressions with the "global" flag. The global flag on the regular expression object causes it to be stateful.

Because the regular expression object is stateful, the following modification to the code in the gist in Comment 0 may be surprising:

> while (regExp.test(str)) {
>   str = str.replace(regExp, pattern);
> }
> print(regExp.test(str)); // prints "true"

Each global regular expression has a "lastIndex" property, which is initialized to zero, set to the end of the last match on success, and reset to zero upon failure. Each match begins from the character at lastIndex -- not from the start (except for str.replace(), which always starts from zero).

So what's happening here is that the regExp.test() in the loop is logically failing prematurely due to the global-ness, despite there still being more to replace. So the next time replace() is called, it has an effect. The solution is to execute a non-global match instead.
Status: UNCONFIRMED → RESOLVED
Last Resolved: 5 years ago
Resolution: --- → INVALID
(Reporter)

Comment 2

5 years ago
Thank you for the tip. Have a nice day !
You need to log in before you can comment on or make changes to this bug.