Document that String.prototype.replace() resets lastIndex for global regexes - #44941
Document that String.prototype.replace() resets lastIndex for global regexes#44941btea wants to merge 1 commit into
Conversation
…regexes Explain that when the pattern is a regex with the g flag, replace() sets the regex's lastIndex to 0 before matching and leaves it at 0 after the call, so there is no need to manually reset lastIndex after using the same regex with methods like test(). Also note that non-global regexes do not get their lastIndex reset. Per ECMA-262: - https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.replace - https://tc39.es/ecma262/#sec-regexp.prototype-@@replace
|
Preview URLs (1 page) |
Josh-Cena
left a comment
There was a problem hiding this comment.
Thanks, but as the paragraph directly preceding your addition says, all behaviors related to the regex itself is documented in the regex reference instead. The String method merely calls that method so this behavior doesn't pertain to it at all. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/Symbol.replace offers a detailed explanation about how lastIndex is changed.
|
Thanks for pointing that out — I hadn't noticed the |
|
One follow-up after re-reading the spec and the current page: the Per ECMA-262
So for global regexes, matching always starts from the beginning of the string regardless of the regex's previous Do you think it is worth adding one sentence to that page, e.g. "If the regex is global, |
|
Yeah, I think that might be worth mentioning. Happy to take another PR! |
|
Opened #44957 to add the note about |
Description
Explain that when the pattern is a regex with the g flag, replace() sets the regex's lastIndex to 0 before matching and leaves it at 0 after the call, so there is no need to manually reset lastIndex after using the same regex with methods like test(). Also note that non-global regexes do not get their lastIndex reset.
Per ECMA-262:
Motivation
Additional details
Related issues and pull requests