0

How can I get all groups of a regex match?

var str = "adam peter james sylvester sarah";
var regex = /what should my regex be t capture all names that has the letter a in them/
var match = regex.exec( text );
console.log(match)

What I want here is each name that has the letter a in it... I want to be able to capture several names preferably at the same time.

Is this possible?

1

2 Answers 2

1

Try my example on Rubular

var str = "adam peter james sylvester sarah";
var match = str.match(/[a-z]*a[a-z]*/gi)
console.log(match)
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, damn. You beat me to it. I was struggling to remember how to format .match(). Here's another valid syntax: str.match(/[a-z]*a[a-z]*/gi)
Sorry, but I have reposted a reformulated question at: stackoverflow.com/questions/14707360/…
0

Regex is probably overkill for this situation. I think it would be simpler to .split() and .indexOf() like so

var names = str.split(" ");
for ( var i=0; i < names.length; i++ ) {
    if ( names[i].indexOf("a") >= 0 ) console.log(names[i]);
}

1 Comment

Sorry, but I have reposted a reformulated question at: stackoverflow.com/questions/14707360/…

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.