Javascript Regex Match Capture is returning whole match, not group

前端 未结 3 1338
心在旅途
心在旅途 2020-12-18 20:24
re = /\\s{1,}(male)\\.$/gi

\"A girl is a female, and a boy is a male.\".match(re);

this results in \" male.\"

what i want is \"male\"

3条回答
  •  隐瞒了意图╮
    2020-12-18 20:58

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

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

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

    Will output:

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

提交回复
热议问题