Ekene Agunechemba

Have you ever played a treasure hunt game — where you scan through words or numbers trying to spot something special? Well, in JavaScript, there’s a magical magnifying glass called .exec(), and it helps you search for hidden treasures inside a string!

Today, you’ll learn how to use it to find, capture, and loop through matches like a true code detective. 🕵️‍♂️


🧠 What is .exec()?

.exec() is a method that works with Regular Expressions (RegEx). It helps you search through a string to find a part that matches a pattern.

Think of it like saying:

“Hey, JavaScript, find me something that looks like THIS!”

Let’s look at an example.

var re = /([0-9]+)[a-z]+/;
var match = re.exec("foo123bar");

This might look like secret code, but here’s the breakdown:

  • /([0-9]+)[a-z]+/ — that’s our pattern:

    • ([0-9]+) means “find one or more numbers”
    • [a-z]+ means “followed by one or more letters”
  • "foo123bar" — that’s the string we’re searching inside

Now .exec() starts scanning like a detective with a flashlight.


💡 Here’s What We Find

When the match is found, .exec() returns an array containing details about what it found:

Property Meaning Example
match[0] The full match "123bar"
match[1] The first captured group "123"
match.index Where the match starts 3

It’s like .exec() says:

“I found something at position 3 — it’s ‘123bar’, and the numbers are ‘123’!”


🎯 Visual Breakdown

String:   f  o  o  1  2  3  b  a  r
Index:    0  1  2  3  4  5  6  7  8
Match:             1  2  3  b  a  r
                  ^ match starts here (index 3)

Now, that’s regex with x-ray vision! 🔍✨


🔁 Finding ALL Matches — The .exec() Loop

What if you don’t want to stop at one match? What if you want to find every “a” in a word?

You can use the g flag (which means “global”) and a loop!

var re = /a/g;
var result;

while ((result = re.exec('barbatbaz')) !== null) {
  console.log("found '" + result[0] + "', next exec starts at index '" + re.lastIndex + "'");
}

🧩 What’s Happening Here?

  • /a/g — means “look for all ‘a’s in the text.”
  • .exec() — finds the first match.
  • .lastIndex — remembers where to start next.
  • The loop keeps running until no more matches are found.

🖨 Output:

found 'a', next exec starts at index '2'
found 'a', next exec starts at index '5'
found 'a', next exec starts at index '8'

Each time .exec() finds an “a”, it moves forward — just like a metal detector beeping along a beach! 🏖️


🍎 Think of It Like a Treasure Hunt

You’re exploring a word, looking for every buried “a”.

Each time you find one, .exec() shouts:

“💎 Found one at spot X! Let’s keep going!”

Then it continues from where it left off until there’s no more treasure to uncover.

That’s how .exec() becomes your pattern-hunting buddy in code!


💪 Let’s Practice a Bit

Try this in your console:

var re = /[A-Z]/g;
var word = "HeLLo World!";
var match;

while ((match = re.exec(word)) !== null) {
  console.log("Found capital letter: " + match[0] + " at position " + match.index);
}

🎉 Watch it list out each capital letter and its position — just like a secret code scanner.


🧠 Key Takeaways

Concept Explanation
.exec() Searches a string for a pattern
Returns An array with the match info, or null if not found
match[0] Full match
match[1] First captured group
match.index Position where match begins
/pattern/g Global search (find all matches)
re.lastIndex Keeps track of where the next search starts

✅ 10 Review Fill-Gap Questions

Let’s test what you remember! Fill in the blanks below 👇

  1. The .exec() method is used to __ a string for a pattern.
  2. If .exec() finds no match, it returns __.
  3. The first element in the result array (match[0]) shows the __ match.
  4. To capture part of a pattern, we use __ in the RegEx.
  5. The g flag in /a/g means __ search.
  6. match.index tells us where the match __.
  7. In the RegEx /([0-9]+)[a-z]+/, the part ([0-9]+) captures one or more __.
  8. The property re.lastIndex stores the position where the __ match will start.
  9. The data type returned by .exec() is an __ if a match is found.
  10. When looping with .exec(), we often use the condition (result = re.exec(string)) !== ______.

<
Previous Post
🔧 Create a Contact Form That Saves to Google Sheets and Sends Emails (With HTML, JS and Apps Script)
>
Next Post
🧠 Python Numbers: Built-in Math Functions and Utility Modules