What is the purpose of the passive (non-capturing) group in a Javascript regex?

后端 未结 5 1835
渐次进展
渐次进展 2021-01-12 11:05

What is the purpose of the passive group in a Javascript regex?

The passive group is prefaced by a question mark colon: (?:group)

In other words

5条回答
  •  渐次进展
    2021-01-12 11:44

    In addition to the answers above, if you're using String.prototype.split() and you use a capturing group, the output array contains the captured results (see MDN). If you use a non-capturing group that doesn't happen.

    var myString = 'Hello 1 word. Sentence number 2.';
    var splits = myString.split(/(\d)/);
    
    console.log(splits);
    

    Outputs:

    ["Hello ", "1", " word. Sentence number ", "2", "."]
    

    Whereas swapping /(\d)/ for /(?:\d)/ results in:

    ["Hello ", " word. Sentence number ", "."]
    

提交回复
热议问题