Skip to content

fix: reset regex lastIndex in pattern() to prevent stateful behavior#1296

Open
Yanhu007 wants to merge 1 commit intoianstormtaylor:mainfrom
Yanhu007:fix/pattern-global-regex-lastindex
Open

fix: reset regex lastIndex in pattern() to prevent stateful behavior#1296
Yanhu007 wants to merge 1 commit intoianstormtaylor:mainfrom
Yanhu007:fix/pattern-global-regex-lastindex

Conversation

@Yanhu007
Copy link
Copy Markdown

Fixes #1190

Problem

When a RegExp with the global (/g) or sticky (/y) flag is passed to pattern(), JavaScript's RegExp.prototype.test() mutates lastIndex after each call, causing alternating results on identical inputs:

const Query = pattern(string(), /^example/g)

is({ url: "example" }, Query) // true
is({ url: "example" }, Query) // false (!)
is({ url: "example" }, Query) // true

This is a well-known JavaScript gotcha.

Fix

Reset lastIndex to 0 before each test() call in the pattern refinement. This ensures consistent results regardless of regex flags.

When a RegExp with the global (/g) or sticky (/y) flag is passed
to pattern(), the regex's lastIndex property is mutated by test(),
causing alternating true/false results on identical inputs.

Reset lastIndex to 0 before each test() call.

Fixes ianstormtaylor#1190
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pattern (regex) does not return consistent output when using the global modifier

1 participant