splitLeft and splitRight

The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern:

"Hello TC39 Discourse Group".split(" ");
Output: ['Hello', 'TC39', 'Discourse', 'Group']

But sometimes we need to divide a String into 2 parts by searching for the pattern:

"Hello TC39 Discourse Group".splitLeft(" ");
Output: ['Hello', 'TC39 Discourse Group']

and splitRight

"Hello TC39 Discourse Group".splitRight(" ");
Output: ['Hello TC39 Discourse', 'Group']

There's: GitHub - tc39/proposal-reversible-string-split: String.prototype.splitn for ECMAScript

Maybe that could accept a negative number to let you splitRight?

"Hello TC39 Discourse Group".splitN(" ", -2); // ['Hello TC39 Discourse', 'Group']
2 Likes

I like that idea, I've prepared a PR for this purpose:

https://github.com/tc39/proposal-reversible-string-split/pull/15