JavaScript Regex Global Match Groups

前端 未结 7 739
感动是毒
感动是毒 2020-11-28 10:50

Update: This question is a near duplicate of this

I\'m sure the answer to my question is out there, but I couldn\'t find the words to express it suc

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 11:37

    String.prototype.matchAll is now well supported in modern browsers as well as Node.js. This can be used like so:

    const matches = Array.from(myString.matchAll(/myRegEx/g)).map(match => match[1]);
    

    Note that the passed RegExp must have the global flag or an error will be thrown.

    Conveniently, this does not throw an error when no matches are found as .matchAll always returns an iterator (vs .match() returning null).


    For this specific example:

    var input = "'Warehouse','Local Release','Local Release DA'";
    var regex = /'(.*?)'/g;
    
    var matches = Array.from(input.matchAll(regex)).map(match => match[1]);
    // [ "Warehouse", "Local Release", "Local Release DA" ]
    

提交回复
热议问题