仅在分隔符的前n次出现时拆分字符串 [英] Split a string only the at the first n occurrences of a delimiter

查看:74
本文介绍了仅在分隔符的前n次出现时拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想仅在分隔符的前n次出现时拆分字符串。我知道,我可以使用循环将它们添加到一起,但是没有更直接的方法吗?

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?

var string = 'Split this, but not this';    
var result = new Array('Split', 'this,', 'but not this');


推荐答案

根据 MDN

string.split(separator, limit);

更新:

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"]

更新版本2(一个切片更短):

Update version 2 (one slice shorter):

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"]

这篇关于仅在分隔符的前n次出现时拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆