JavaScript equivalent of Python's rsplit

Question:

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

Asked By: Jesse Aldridge

||

Answers:

Assuming the semantics of JavaScript split are acceptable use the following

String.prototype.rsplit = function (delimiter, limit) {
  delimiter = this.split (delimiter || /s+/);
  return limit ? delimiter.splice (-limit) : delimiter;
} 
Answered By: HBP
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’ ]

Answered By: 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'

Answered By: Rushabh Mehta

i think this is more "equivalent" until a bug is found, "close" is not acceptable for an answer.

String.prototype.rsplit = function(sep, maxsplit) {
    var result = []
    if ( (sep === undefined) ) {
        sep = " "
        maxsplit = 0
    }

    if (maxsplit === 0  )
        return [this]

    var data = this.split(sep)


    if (!maxsplit || (maxsplit<0) || (data.length==maxsplit+1) )
        return data

    while (data.length && (result.length < maxsplit)) {
        result.push( data.pop() )
    }
    if (result.length) {
        result.reverse()
        if (data.length>1) {
            return [data.join(sep), result ]
        }
        return result
    }
    return [this]
}
Answered By: Pmp P.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.