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?

mjs
  • 21,431
  • 31
  • 118
  • 200
  • Sorry, but I have reposted a reformulated question at: http://stackoverflow.com/questions/14707360/javascript-regex-multiple-captures-again Please see that to see what I have tried. – mjs Feb 05 '13 at 12:18

2 Answers2

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)
grigno
  • 3,128
  • 4
  • 35
  • 47
  • 1
    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)` – m.brindley Feb 05 '13 at 11:11
  • Sorry, but I have reposted a reformulated question at: http://stackoverflow.com/questions/14707360/javascript-regex-multiple-captures-again – mjs Feb 05 '13 at 12:17
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]);
}
m.brindley
  • 1,218
  • 10
  • 19
  • Sorry, but I have reposted a reformulated question at: http://stackoverflow.com/questions/14707360/javascript-regex-multiple-captures-again – mjs Feb 05 '13 at 12:18