相当于Python rsplit的Javascript

时间:2022-06-01 03:11:47

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

str.rsplit([[,maxsplit]]9月)

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.

返回字符串中的单词列表,使用sep作为分隔符字符串。如果maxsplit是给定的,那么最多只做maxsplit split,最右边的。如果没有指定sep或没有,则任何空格字符串都是分隔符。除了从右边分裂之外,rsplit()的行为与split()类似,下文将对此进行详细描述。

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

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

3 个解决方案

#1


11  

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

这个函数更接近于Python版本

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

“胡说,胡说,derp beep”.rsplit("、",1)/ /[derp胡说,胡说,“哔哔”)

#2


2  

Assming the semantics of JavaScript split are acceptable use the following

可以使用以下方法对JavaScript拆分的语义进行分析

String.prototype.rsplit = function (delimiter, limit) {
  delimiter = this.split (delimiter || /s+/);
  return limit ? delimiter.splice (-limit) : delimiter;
} 

#3


2  

You can also use JS String functions split + slice

您还可以使用JS字符串函数split + slice

Python:

Python:

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

“a,b,c”。rsplit(',' -1)[0]会得到'a,b'

Javascript:

Javascript:

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

“a,b,c”.split(" ")。切片(0,-1).join(',')也会给你a,b'

#1


11  

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

这个函数更接近于Python版本

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

“胡说,胡说,derp beep”.rsplit("、",1)/ /[derp胡说,胡说,“哔哔”)

#2


2  

Assming the semantics of JavaScript split are acceptable use the following

可以使用以下方法对JavaScript拆分的语义进行分析

String.prototype.rsplit = function (delimiter, limit) {
  delimiter = this.split (delimiter || /s+/);
  return limit ? delimiter.splice (-limit) : delimiter;
} 

#3


2  

You can also use JS String functions split + slice

您还可以使用JS字符串函数split + slice

Python:

Python:

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

“a,b,c”。rsplit(',' -1)[0]会得到'a,b'

Javascript:

Javascript:

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

“a,b,c”.split(" ")。切片(0,-1).join(',')也会给你a,b'