Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript equivalent of Python's rsplit

Tags:

str.rsplit([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.

http://docs.python.org/library/stdtypes.html#str.rsplit

like image 629
Jesse Aldridge Avatar asked Mar 05 '11 06:03

Jesse Aldridge


2 Answers

String.prototype.rsplit = function(sep, maxsplit) {
    var split = this.split(sep);
    return maxsplit ? [ split.slice(0, -maxsplit).join(sep) ].concat(split.slice(-maxsplit)) : split;
}

This one functions more closely to the Python version

"blah,derp,blah,beep".rsplit(",",1) // [ 'blah,derp,blah', 'beep' ]

like image 152
Morgan ARR Allen Avatar answered Sep 22 '22 00:09

Morgan ARR Allen


You can also use JS String functions split + slice

Python:

'a,b,c'.rsplit(',' -1)[0] will give you 'a,b'

Javascript:

'a,b,c'.split(',').slice(0, -1).join(',') will also give you 'a,b'

like image 41
Rushabh Mehta Avatar answered Sep 21 '22 00:09

Rushabh Mehta