我想在分隔符的前n次出现时只分割一个字符串.我知道,我可以使用循环将它们添加到一起,但是不是更直接的方法吗?
var string = 'Split this, but not this';
var result = new Array('Split', 'this,', 'but not this');
Run Code Online (Sandbox Code Playgroud)
dav*_*vin 35
根据MDN:
string.split(separator, limit);
Run Code Online (Sandbox Code Playgroud)
更新:
var string = 'Split this, but not this',
arr = string.split(' '),
result = arr.slice(0,2);
result.push(arr.slice(2).join(' ')); // ["Split", "this,", "but not this"]
Run Code Online (Sandbox Code Playgroud)
更新版本2(一个slice更短):
var string = 'Split this, but not this',
arr = string.split(' '),
result = arr.splice(0,2);
result.push(arr.join(' ')); // result is ["Split", "this,", "but not this"]
Run Code Online (Sandbox Code Playgroud)
Laa*_*aas 19
使用Array.slice:
function splitWithTail(str,delim,count){
var parts = str.split(delim);
var tail = parts.slice(count).join(delim);
var result = parts.slice(0,count);
result.push(tail);
return result;
}
Run Code Online (Sandbox Code Playgroud)
结果:
splitWithTail(string," ",2)
// => ["Split", "this,", "but not this"]
Run Code Online (Sandbox Code Playgroud)
JavaScript".split()"函数已经接受第二个参数,给出要执行的最大拆分数.但是,它不会保留原始字符串的尾端; 你必须重新粘上它.
另一种方法是用正则表达式迭代地剪掉字符串的前导部分,当你获得限制时停止.
var str = "hello out there cruel world";
var parts = [];
while (parts.length < 3) { // "3" is just an example
str = str.replace(/^(\w+)\s*(.*)$/, function(_, word, remainder) {
parts.push(word);
return remainder;
});
}
parts.push(str);
Run Code Online (Sandbox Code Playgroud)
编辑 - 它只是发生在我身上,另一个简单的方法就是使用普通的".split()",取出前几个部分,然后只是".slice()"和".join()"其余部分.
结合使用ES6 split和joinES6具有以下功能:
let [str1, str2, ...str3] = string.split(' ');
str3 = str3.join(' ');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26316 次 |
| 最近记录: |