search() with Regular Expressions
What you'll learn: How to use search() to find the position of a pattern match in a string using regular expressions.
The Core Idea
The search() method is like indexOf(), but supercharged with pattern-matching abilities. Instead of searching for exact text, you can search for patterns using regular expressions (regex). It returns the index of the first match, or -1 if nothing matches.
Think of it like using "Find" in a document editor with a pattern rule instead of exact words — searching for "any three digits" rather than just "123".
How It Works
let text = "My phone is 555-1234";
let position = text.search(/\d/);
console.log(position); // 12 (first digit found)
The /\d/ is a regular expression pattern that means "any digit character." The search() method scans the string from left to right and returns 12 — the index where the first digit appears.
Key Differences from indexOf()
Unlike indexOf(), which only finds exact strings:
search()accepts regex patterns for flexible matching- It always returns the position of the first match only
- Returns
-1when no match is found
let greeting = "Hello World";
greeting.search(/world/i); // 6 (case-insensitive match)
greeting.indexOf("world"); // -1 (case-sensitive, no match)
The /i flag makes the search case-insensitive.
When to Use It
Use search() when you need to find where a pattern starts, not just exact text. Perfect for locating the first number, special character, or complex pattern in a string.
Key Takeaway: search() finds the index of the first regex pattern match in a string, returning -1 if no match exists — it's pattern-powered positioning.