Javascript Regex Match Capture returns the entire match, not the group

re = /\s{1,}(male)\.$/gi "A girl is a female, and a boy is a male.".match(re); 

this leads to a "man."

what i want, "man"

I put the man in parentheses, and I, although this will only capture this group.

thanks for the help

+7
source share
2 answers

You need to take out the 'g' option in your regular expression:

 re = /\s{1,}(male)\.$/i 

gives

 [" male.", "male"] 
+9
source

In String.prototype.match (), the captured groups are not returned.

If you need capture groups, use RegExp.prototype.exec (). It will return an array, the first element will be a complete match, and the following elements will capture capture groups.

 var regexObj = /\s{1,}(male)\.$/gi; console.log(regexObj.exec('A girl is a female, and a boy is a male.')); 

It will display:

[' male.', 'male'] // Second element is your capture group

-one
source

All Articles