Javascript 在javascript中拆分字符串一次?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2878703/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:18:41  来源:igfitidea点击:

Split string once in javascript?

javascriptsplit

提问by Stavros Korokithakis

How can I split a string only once, i.e. make 1|Ceci n'est pas une pipe: | Ouiparse to: ["1", "Ceci n'est pas une pipe: | Oui"]?

如何只拆分字符串一次,即1|Ceci n'est pas une pipe: | Oui解析为:["1", "Ceci n'est pas une pipe: | Oui"]

The limit in split doesn't seem to help...

split 的限制似乎没有帮助......

采纳答案by Nick Craver

This isn't a pretty approach, but works with decent efficiency:

这不是一个很好的方法,但工作效率不错:

var string = "1|Ceci n'est pas une pipe: | Oui";
var components = string.split('|');
alert([components.shift(), components.join('|')]?);?????

Here's a quick demo of it

这是它的快速演示

回答by yarmiganosca

You'd want to use String.indexOf('|')to get the index of the first occurrence of '|'.

您想用它String.indexOf('|')来获取第一次出现“|”的索引。

var i = s.indexOf('|');
var splits = [s.slice(0,i), s.slice(i+1)];

回答by Matthew Flaschen

You can use:

您可以使用:

var splits = str.match(/([^|]*)\|(.*)/);
splits.shift();

The regex splits the string into two matching groups (parenthesized), the text preceding the first | and the text after. Then, we shiftthe result to get rid of the whole string match (splits[0]).

正则表达式将字符串拆分为两个匹配组(带括号),第一个 | 之前的文本 和后面的文字。然后,我们shift把整个字符串的匹配结果去掉(splits[0])。

回答by Hassek

one liner and imo, simpler:

一个班轮和海事组织,更简单:

var str = 'I | am super | cool | yea!';
str.split('|').slice(1).join('|');

This returns " am super | cool | yea!"

这将返回“我超级 | 酷 | 是的!”

回答by andyhasit

ES6 syntax allows a different approach:

ES6 语法允许采用不同的方法:

function splitOnce(s, on) {
   [first, ...rest] = s.split(on)
   return [first, rest.length > 0? rest.join(on) : null]
}

Which also handles the eventuality of the string not having a |by returning null rather than an empty string, which is more explicit.

它还|通过返回 null 而不是空字符串来处理没有 a 的字符串的可能性,这是更明确的。

splitOnce("1|Ceci n'est pas une pipe: | Oui", "|")
>>> ["1", "Ceci n'est pas une pipe: | Oui"]

splitOnce("Celui-ci n'a pas de pipe symbol!", "|")
>>> ["Celui-ci n'a pas de pipe symbol!", null]

Pas de pipe? C'est null!

管道?C'est null!

I added this reply primarily so I could make a pun on the pipe symbol, but also to show off es6 syntax - its amazing how many people still don't use it...

我添加了这个回复主要是为了我可以在管道符号上打个双关语,但也为了炫耀 es6 语法 - 令人惊讶的是有多少人仍然不使用它......

回答by Raine Revere

If the string doesn't contain the delimiter @NickCraver's solution will still return an array of two elements, the second being an empty string. I prefer the behavior to match that of split. That is, if the input string does not contain the delimiter return just an array with a single element.

如果字符串不包含分隔符@NickCraver 的解决方案仍将返回一个包含两个元素的数组,第二个是一个空字符串。我更喜欢这种行为来匹配 split 的行为。也就是说,如果输入字符串不包含分隔符,则只返回一个包含单个元素的数组。

var splitOnce = function(str, delim) {
    var components = str.split(delim);
    var result = [components.shift()];
    if(components.length) {
        result.push(components.join(delim));
    }
    return result;
};

splitOnce("a b c d", " "); // ["a", "b c d"]
splitOnce("a", " "); // ["a"]

回答by Josh the Goods

Try this:

尝试这个:

function splitOnce(input, splitBy) {
    var fullSplit = input.split(splitBy);
    var retVal = [];
    retVal.push( fullSplit.shift() );
    retVal.push( fullSplit.join( splitBy ) );
    return retVal;
}

var whatever = splitOnce("1|Ceci n'est pas une pipe: | Oui", '|');

回答by wombleton

Just as evil as most of the answers so far:

与迄今为止的大多数答案一样邪恶:

var splits = str.split('|');
splits.splice(1, splits.length - 1, splits.slice(1).join('|'));

回答by wombleton

An alternate, short approach, besides the goods ones elsewhere, is to use replace()'s limit to your advantage.

除了其他地方的商品之外,另一种简短的方法是利用replace()'s limit 来获得优势。

var str = "1|Ceci n'est pas une pipe: | Oui";
str.replace("|", "aUniquePhraseToSaySplitMe").split("aUniquePhraseToSaySplitMe");

As @sreservtheitroad points out in the comments, the unique phrase must be truly unique--it cannot be in the source you're running this split over, or you'll get the string split into more pieces than you want. An unprintable character, as he says, may do if you're running this against user input (i.e., typed in a browser).

正如@sreservtheitroad 在评论中指出的那样,唯一的短语必须是真正唯一的——它不能在您运行此拆分的源中,否则您会将字符串拆分成比您想要的更多的部分。正如他所说,如果您针对用户输入(即在浏览器中输入)运行它,则可能会出现无法打印的字符。

回答by alfadog67

This one's a little longer, but it works like I believe limit should:

这个有点长,但它的工作原理就像我相信 limit 应该:

function split_limit(inString, separator, limit){
    var ary = inString.split(separator);
    var aryOut = ary.slice(0, limit - 1);
    if(ary[limit - 1]){
        aryOut.push(ary.slice(limit - 1).join(separator));
    }
    return aryOut;
}
console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 1));
console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 2));
console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 3));
console.log(split_limit("1|Ceci n'est pas une pipe: | Oui","|", 7));

https://jsfiddle.net/2gyxuo2j/

https://jsfiddle.net/2gyxuo2j/

limit of Zero returns funny results, but in the name of efficiency, I left out the check for it. You can add this as the first line of the function if you need it:

零的限制返回有趣的结果,但为了效率,我省略了检查。如果需要,您可以将其添加为函数的第一行:

if(limit < 1) return [];