javascriptpythonstringsplit

JavaScript equivalent of Python's rsplit


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


Solution

  • 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' ]