Sometimes, we want to add the JavaScript equivalent of Python’s rsplit
method.
In this article, we’ll look at how to add the JavaScript equivalent of Python’s rsplit
method.
How to add the JavaScript equivalent of Python’s rsplit method?
To add the JavaScript equivalent of Python’s rsplit
method, we can create our own function.
Fir instance, we write:
const rsplit = (str, sep, maxsplit) => {
const split = str.split(sep);
return maxsplit ? [split.slice(0, -maxsplit).join(sep)].concat(split.slice(-maxsplit)) : split;
}
const a = rsplit("blah,derp,blah,beep", ",", 1)
console.log(a)
to create the rsplit
function.
In it, we call str.split
with the sep
separator to split the string into an array.
Then we combine the string with split.slice(0, -maxsplit).join(sep)
concatenated with split.slice(-maxsplit)
to return an array with the combined and split string.
If maxsplit
isn’t set, then we return the split
array as is.
Therefore, we get ['blah,derp,blah', 'beep']
from the console log.
Conclusion
To add the JavaScript equivalent of Python’s rsplit
method, we can create our own function.