Finding a substring and checking an entire input are different jobs. An anchor makes a regular expression match at a position rather than consuming a character. Use `^` at the start of a pattern to require the beginning of the string, and `$` to require its end. section 12.2.2
Substring or whole string?
`/^test/` matches `testing`, but not `pretest`. `/test$/` matches `pretest`, but not `testing`. `/^test$/` matches only `test`: the pattern must span the entire candidate string. Anchors also work with repetition: `/^t?est$/` accepts `test` and `est`, but no extra characters. section 12.2.2 section 12.2.2
Position matters for words, too. `\b` matches the boundary between a word character and a non-word character or a string edge; it does not match a character itself. In `/\b([a-z]+) \1\b/i`, the boundaries keep the repeated-word match from picking `doki doki` out of longer adjoining words. Here `\1` refers back to the captured word. Do not confuse `^` at the start of a regex with `^` inside a character class such as `[^abc]`, where it negates the class. section 12.4.3 section 12.2.2
Anchoring an entire input does not guarantee a quick rejection. With `/^(?:\w+\s*)+$/`, a trailing `!` prevents the end anchor from matching after an otherwise plausible sequence of words. The regex can then backtrack through many ways of grouping the preceding characters; the optional whitespace adds possibilities. Check the repetition structure as well as the anchors when a full-string test runs slowly. section 12.6.3
Listing 12.13 A regex with catastrophic backtracking
const rosterRegex = /^(?:\w+\s*)+$/; #A
console.assert( #B
rosterRegex.test("Hattori Yoshi Fuma"), #B
"A genuine roster is accepted instantly", #B
); #B
const attack = #C
"I will erase your existence from this realm!"; #C
const start = performance.now(); #C
rosterRegex.test(attack); #C
const elapsed = performance.now() - start; #C
console.log(
`Rejecting the attack string took ${elapsed.toFixed(0)}ms`,
);
Run the timed JavaScript example to compare immediate acceptance of a word roster with slow rejection of an input ending in `!`. section 12.6.3



