限制.split()拆分的时间,而不是截断结果数组 [英] Limiting the times that .split() splits, rather than truncating the resulting array

查看:48
本文介绍了限制.split()拆分的时间,而不是截断结果数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的,标题说的差不多.

Really, pretty much what the title says.

假设您有以下字符串:

var theString = "a=b=c=d";

现在,当您运行theString.split("=")时,结果将是预期的["a", "b", "c", "d"].而且,当然,当您运行theString.split("=", 2)时,您会得到["a", "b"],它是在阅读

Now, when you run theString.split("=") the result is ["a", "b", "c", "d"] as expected. And, of course, when you run theString.split("=", 2) you get ["a", "b"], which after reading the MDN page for String#split() makes sense to me.

但是,我要寻找的行为更像Java的String#split():与其正常构建数组,然后返回第一个 n 元素,不如构建第一个的数组> n-1 匹配,然后将所有剩余字符添加为数组的最后一个元素.请参见相关文档以获取更好的说明.

However, the behavior I'm looking for is more like Java's String#split(): Instead of building the array normally, then returning the first n elements, it builds an array of the first n-1 matches, then adds all the remaining characters as the last element of the array. See the relevant docs for a better description.

如何在Javascript中获得这种效果?

How can I get this effect in Javascript?

我正在寻找具有与Java实现类似的最佳性能的答案,尽管其实际工作方式可能有所不同.

I'm looking for the answer with the best performance that works like the Java implementation, though the actual way it works can be different.

我会发表自己的尝试,但是我根本不知道该怎么写.

I'd post my attempt, but I don't know how to go about writing this at all.

推荐答案

如果要获得与Java实现完全相同的内容(无错误检查或保护子句等):

If you want the exact equivalent of the Java implementation (no error checking or guard clauses etc):

function split(str, sep, n) {
    var out = [];

    while(n--) out.push(str.slice(sep.lastIndex, sep.exec(str).index));

    out.push(str.slice(sep.lastIndex));
    return out;
}

console.log(split("a=b=c=d", /=/g, 2)); // ['a', 'b', 'c=d']

如您在问题中提到的那样,这样做还有一个好处,就是无需预先计算完整的拆分.

This has the added benefit of not computing the complete split beforehand, as you mentioned in your question.

这篇关于限制.split()拆分的时间,而不是截断结果数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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