Question presented to candidate: "If you create a regex with the global flag and call .test() on it three times in a row against the SAME short string, does it always return true? Walk me through what actually happens internally."
What a strong answer should cover:
- 📌 Interview term: a regex literal (
/pattern/flags) — matches text against a pattern; common methods are.test()(boolean),.exec()(a full match object ornull), and the string methods.match()/.matchAll()/.replace(). - 📌 Interview term: the real, direct answer to the prompt — verified directly: with the global (
g) flag,.test()/.exec()are genuinely stateful — each call advances a real, persistentlastIndexproperty on the regex object itself, continuing the search from there on the NEXT call. Verified directly with 3 sequential real.test()calls against"xx": the answer is genuinely not alwaystrue— the third call genuinely returnedfalse, becauselastIndexhad advanced past the end of the string, at which point it automatically resets to0. - 📌 Interview term: capture groups — parentheses
(...)create numbered capture groups, retrievable from a match — verified directly with a real date-parsing example; named capture groups ((?<name>...)) are also verified directly, retrievable via the match's own.groupsobject. - 📌 Interview term:
match()withgvs.matchAll()— verified directly:str.match(/pattern/g)returns only the matched STRINGS, losing capture-group/index info, whilematchAll()returns full match objects (with groups and index) for every match, genuinely richer information. - A precise answer names the real, common practical use of a capture-group-referencing
.replace()($1,$2, named-group syntax) for reformatting matched text — verified directly, reformatting a date string using its own captured pieces.
Clarifying questions expected:
- None — this is a definitional/technical question; directly answering the prompt's own 3-calls scenario (and correctly explaining WHY the third call differs) is the strong signal, since global-flag statefulness is the single most commonly missed regex detail.
Code / implementation expected: Yes — the real, sequential 3-call .test() demonstration against the same short string is the clearest, most convincing proof of the exact statefulness behavior.