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
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' ]
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'
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;
}
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]
}
精彩评论