Javascript 仅在分隔符的前 n 个出现处拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5582248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split a string only the at the first n occurrences of a delimiter
提问by nines
I'd like to split a string only the at the first n occurrences of a delimiter. I know, I could add them together using a loop, but isn't there a more straight forward approach?
我想仅在分隔符的前 n 次出现时拆分字符串。我知道,我可以使用循环将它们加在一起,但是没有更直接的方法吗?
var string = 'Split this, but not this';
var result = new Array('Split', 'this,', 'but not this');
回答by davin
As per MDN:
根据MDN:
string.split(separator, limit);
Update:
更新:
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"]
Update version 2 (one slice
shorter):
更新版本 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"]
回答by Laas
Using Array.slice:
使用 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;
}
Results:
结果:
splitWithTail(string," ",2)
// => ["Split", "this,", "but not this"]
回答by Pointy
The JavaScript ".split()" function already accepts a second parameter giving the maximum number of splits to perform. However, it doesn't retain the tail end of your original string; you'd have to glue it back on.
JavaScript“.split()”函数已经接受了第二个参数,给出了要执行的最大拆分次数。但是,它不会保留原始字符串的尾端;你得把它粘回去。
Another approach would be to iteratively shave off a leading portion of the string with a regex, stopping when you've gotten your limit.
另一种方法是用正则表达式迭代地去除字符串的前导部分,当你达到极限时停止。
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);
edit— and it just occurs to me that another simple way would be to just use plain ".split()", pluck off the first few parts, and then just ".slice()" and ".join()" the rest.
编辑——我突然想到另一种简单的方法是使用简单的“.split()”,去掉前几个部分,然后只使用“.slice()”和“.join()”其余部分.
回答by Eugene Gluhotorenko
Combination of split
and join
with ES6 features does this pretty neat:
结合split
并join
用ES6功能做到这一点非常简洁:
let [str1, str2, ...str3] = string.split(' ');
str3 = str3.join(' ');
回答by clamchoda
For this you could use Split(delimiter) and choose a delimiter.
为此,您可以使用 Split(delimiter) 并选择一个分隔符。
var testSplit = "Split this, but not this";
var testParts= testSplit.Split(",");
var firstPart = testParts[1];
// firstPart = "Split this"
Not 100% on my syntax I havent used javascript in quite some time. But I know this is how its done...
我的语法不是 100% 我已经有一段时间没有使用 javascript 了。但我知道这就是它的完成方式......
EDIT** Sorry, my mistake. Now I believe I know what your asking and I think the easiest way to do this is using substr. Very easy, no loops required. Just made an example, works perfect
编辑**对不起,我的错误。现在我相信我知道你在问什么,我认为最简单的方法是使用 substr。非常简单,不需要循环。刚刚做了一个例子,完美的作品
// so first, we want to get everything from 0 - the first occurence of the comma.
// next, we want to get everything after the first occurence of the comma. (if you only define one parameter, substr will take everything after that parameter.
var testString = "Split this, but this part, and this part are one string";
var part1 = testString.substr(0,testString.indexOf(','));
var part2 = testString.substr(testString.indexOf(','));
//part1 = "Split this"
//part2= "but this part, and this part are one string"
回答by Naveed Ul Islam
var result = [string.split(' ',1).toString(), string.split(' ').slice(1).join(' ')];
Results in:
结果是:
["Split", "this, but not this"]
回答by T.J. Crowder
Although you can give split
a limit, you won't get back what you've said you want. Unfortunately, you will have to roll your own on this, e.g.:
虽然你可以给split
一个限制,但你不会得到你所说的你想要的。不幸的是,您必须自己动手,例如:
var string = 'Split this, but not this';
var result = string.split(' ');
if (result.length > 3) {
result[2] = result.slice(2).join(' ');
result.length = 3;
}
But even then, you end up modifying the number of spaces in the latter parts of it. So I'd probably just do it the old-fashioned write-your-own-loop way:
但即便如此,您最终还是要修改它后面部分的空格数。所以我可能只是按照老式的 write-your-own-loop 方式来做:
function splitWithLimit(str, delim, limit) {
var index,
lastIndex = 0,
rv = [];
while (--limit && (index = str.indexOf(delim, lastIndex)) >= 0) {
rv.push(str.substring(lastIndex, index));
lastIndex = index + delim.length;
}
if (lastIndex < str.length) {
rv.push(str.substring(lastIndex));
}
return rv;
}
回答by Maertz
Hi there i had the same problem wanted to split only several times, couldnt find anything so i just extended the DOM - just a quick and dirty solution but it works :)
嗨,我有同样的问题,只想拆分几次,找不到任何东西,所以我只是扩展了 DOM - 只是一个快速而肮脏的解决方案,但它有效:)
String.prototype.split = function(seperator,limit) {
var value = "";
var hops = [];
// Validate limit
limit = typeof(limit)==='number'?limit:0;
// Join back given value
for ( var i = 0; i < this.length; i++ ) { value += this[i]; }
// Walkthrough given hops
for ( var i = 0; i < limit; i++ ) {
var pos = value.indexOf(seperator);
if ( pos != -1 ) {
hops.push(value.slice(0,pos));
value = value.slice(pos + seperator.length,value.length)
// Done here break dat
} else {
break;
}
}
// Add non processed rest and return
hops.push(value)
return hops;
}
In your case would look like that
在你的情况下看起来像那样
>>> "Split this, but not this".split(' ',2)
["Split", "this,", "but not this"]
回答by Thomas Bachem
Improved version of a sane limit
implementation with proper RegEx support:
limit
具有适当 RegEx 支持的理智实现的改进版本:
function splitWithTail(value, separator, limit) {
var pattern, startIndex, m, parts = [];
if(!limit) {
return value.split(separator);
}
if(separator instanceof RegExp) {
pattern = new RegExp(separator.source, 'g' + (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : ''));
} else {
pattern = new RegExp(separator.replace(/([.*+?^${}()|\[\]\/\])/g, '\'), 'g');
}
do {
startIndex = pattern.lastIndex;
if(m = pattern.exec(value)) {
parts.push(value.substr(startIndex, m.index - startIndex));
}
} while(m && parts.length < limit - 1);
parts.push(value.substr(pattern.lastIndex));
return parts;
}
Usage example:
用法示例:
splitWithTail("foo, bar, baz", /,\s+/, 2); // -> ["foo", "bar, baz"]
Built for & tested in Chrome, Firefox, Safari, IE8+.
专为 Chrome、Firefox、Safari、IE8+ 构建并经过测试。
回答by K-Gun
Yet another implementation with limit;
又一个有限制的实现;
// takes string input only
function split(input, separator, limit) {
input = input.split(separator);
if (limit) {
input = input.slice(0, limit - 1).concat(input.slice(limit - 1).join(separator));
}
return input;
}