Skip to content Skip to sidebar Skip to footer

What Is The Precise Definition Of Javascript's String.split?

Something worked for me today, but I'm not sure that I understand it enough to be certain that it will work in random future versions of Javascript. I wanted something like string.

Solution 1:

If the argument to split is a regex with capturing groups, the matched groups are returned as individual items in the return array. Moreover, if the regex contains multiple capturing groups, they'll all be included in the return array as individual elements.

let input = 'a 8_b 0_c';
console.log(input.split(/ \d_/));
console.log(input.split(/ (\d)_/)); // includes numbersconsole.log(input.split(/( )(\d)_/)); // includes spaces and numbersconsole.log(input.split(/( )(\d)(_)/)); // includes spaces, numbers, and underscores

So for your use case, you can simplify your solution to

let x = "abc   def ghi".split(/(\s+)/);
console.log(x);

MDN reference

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array.

Post a Comment for "What Is The Precise Definition Of Javascript's String.split?"