1

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];
}
1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.