Ktown
Ktown

Reputation: 109

Regex .exec into array

I want to capture some values in a string, THEN return them to the page. Here is an example of the code. As I understand, the .exec should store the values it matches into the array correct? This should return Savage, Betsy. Can someone enlighten me on to what's wrong?

var regex = /\b(Betsy)(Savage)\b/i;

var string = "My friend is Betsy Ann Savage";

var arrayMatch = null;

while(arrayMatch = regex.exec(string)){
   document.getElementById("text").innerHTML = arrayMatch[1] + ", " + arrayMatch[0];
}

Upvotes: 1

Views: 209

Answers (2)

Wouter van Nifterick
Wouter van Nifterick

Reputation: 24116

You don't get any matches like this. You could add .* between (Betsy) and (Savage)...

Upvotes: 2

sircodesalot
sircodesalot

Reputation: 11439

It sounds like you think \b(Besty)(Savage)\b will match EITHER Besty, OR Savage, but that isn't the case. It's looking for one string where both parts are combined - you might as well try to match \b(BetsySavage)\b. This is because a while yes, you do have two groups separated by parentasis, you have them directly next to each other, so the Regex engine says, 'okay', I'll look for both right next to each other. I think what you really want to do is use | which represents an OR. As in \b(Besty|Savage)\b.

Upvotes: 0

Related Questions