Javascript split can keep splitted value?

后端 未结 2 1916
无人共我
无人共我 2021-01-14 03:09

In Javascript :

var myString = \"This is my string\";

console.log(myString.split(/(\\s)/));

Output : [\"This\", \" \", \"is\", \" \"

相关标签:
2条回答
  • 2021-01-14 03:13

    The two regexs you're using are only slightly different.

    /(\s)/ has a capture group of \s, so when used with split() it will add the anything found in the capture group to the array.

    The regex /\s/ has no capture group, so split() ignores the matches and does not add them to the array.

    Similarly, if you execute:

    var myString = "This is my string";
    
    console.log(myString.split(/(my)/));  //includes matched capture group in results
    console.log(myString.split(/my/));  //ignores matches
    

    Will output:

    ["This is ", "my", " string"]
    ["This is ", " string"]

    Hope that helps!

    0 讨论(0)
  • 2021-01-14 03:15

    If you use a "capturing" group for the split pattern then the assumption is that probably you're interested in the group and therefore Javascript adds the group to the result.

    If for example you use a "non-capturing" group instead then the result of the split is the same as when not using a group at all..

    "This is my string".split(/(?:\s)/) → ["This", "is", "my", "string"]
    

    Indeed there can be cases in which you may need a capturing group for the match (e.g. if you need a back-reference) but you're not interested in the separators. The workaround in those cases is to simply keep every other element of the result.

    0 讨论(0)
提交回复
热议问题