Finding a pattern is useful; keeping the part that matched lets you inspect or transform it. Parentheses group terms in a regular expression and, by default, capture the text matched by that group. In /(ab)+/, the parentheses let + apply to the whole ab sequence while also creating a capture. section 12.2.2 section 12.4
Read the match and its capture
const found = "It's over 9000!".match(/(\d+)/); console.assert(found?.[0] === "9000"); console.assert(found?.[1] === "9000"); Index 0 holds the full match; the parenthesized group supplies a capture. Check for null before reading a result when a match is not guaranteed. section 12.3 section 12.7
Choose the kind of group and the way you use its result:
- Use (?:...) when terms need grouping but their match need not be captured. section 12.7
- Use \1, \2, and so on to require text captured earlier in the same pattern. /^([dtn])a\1/ requires the character after a to repeat the first captured character—not merely belong to the same character class. section 12.2.2
- Use match for a local regex or matchAll for a global one. A replace callback can receive the full match, each capture, the match index, and the source string. section 12.7 section 12.5
Listing 12.8 Using a replacer function to transform a string
const kebabCaseRegex = /-([a-z])/g; #A const technique = "shadow-clone-jutsu"; const camelCase = technique.replace( #B kebabCaseRegex, #B (_, letter: string) => letter.toUpperCase(), #B ); #B console.assert( camelCase === "shadowCloneJutsu", "The kebab-case string becomes 'shadowCloneJutsu'", );
A global pattern captures each letter after a hyphen. The replacement callback uppercases that capture, turning shadow-clone-jutsu into shadowCloneJutsu. Its unused first parameter still needs a placeholder: function arguments cannot be skipped like array-destructuring positions. section 12.5
