String Methods That Accept Regex
You'll learn how JavaScript strings have built-in methods that leverage regular expressions for powerful text manipulation.
Why This Matters
While test() and exec() live on the regex object itself, JavaScript strings have their own methods that accept regex patterns as arguments. These methods give you different ways to search, replace, split, and extract text—making regex even more versatile.
The Four Key String Methods
search()
Returns the index of the first match, or -1 if not found. Think of it like indexOf(), but with regex superpowers:
const text = "The price is $50";
const position = text.search(/\$\d+/);
console.log(position); // 13
replace()
Substitutes matches with new text. Use the g flag to replace all occurrences:
const messy = "hello world there";
const clean = messy.replace(/\s+/g, " ");
console.log(clean); // "hello world there"
split()
Breaks a string into an array using a regex as the delimiter:
const data = "apple,banana;cherry|date";
const fruits = data.split(/[,;|]/);
console.log(fruits); // ["apple", "banana", "cherry", "date"]
matchAll()
Returns an iterator of all matches with full details (requires the g flag):
const text = "cat bat rat";
const matches = [...text.matchAll(/\b\w+at\b/g)];
console.log(matches.length); // 3
console.log(matches[0][0]); // "cat"
Key Takeaway: JavaScript strings have search(), replace(), split(), and matchAll() methods that accept regex patterns, giving you flexible tools for finding, transforming, and extracting text directly from strings.