Skip to content Skip to sidebar Skip to footer

Javascript Regex Group Multiple

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/ va

Solution 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)

Solution 2:

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

Post a Comment for "Javascript Regex Group Multiple"