根据长度将字符串分成多个数组(javascript)

时间:2019-07-21 13:53:47

标签: javascript arrays string sorting split

我有一个长度可变的字符串,对于这个问题,我将简单地保留它,并假设列表中有一小部分项目。

目标是拆分字符串以创建长度大于11的多个字符串值,但是我需要保留逗号值(例如,我不能只拆分每11个字符,我必须在最后拆分第11个字符前的逗号

test1,test2,test3,test4,test5

出于参数的考虑,让我们建议字符串的最大长度可以为10个字符,因此在此示例中,以上内容将转换为三个单独的字符串:

test1,test2

test3,test4

test5

为明确起见,每个拆分值最大允许字符限制为11个字符,但我们希望尽可能高效地使用这些字符。

3 个答案:

答案 0 :(得分:2)

您可以使用(当您希望将最小长度视为10,并希望继续到下一个即将出现的字符串或字符串结尾时)

(.{10,}?)(?:,|$)

enter image description here

const input = 'test1,test2,test3,test4,test5';
console.log(
  input.split(/(.{10,}?)(?:,|$)/g).filter(Boolean)
);


更新:- 由于您希望该值介于某个范围内,因此可以使用

(.{1,22})(?:,|$)

Demo

答案 1 :(得分:0)

我不确定您是否正在寻找类似的东西。但是此代码根据您的示例给出了输出:

// Try edit msg
var msg = 'test1,test2,test3,test4,test5'

msgs = msg.split(",")

final = []
str = ""
msgs.map( m => {
  str += str == "" ? m : "," + m
  if (str.length > 10){
    final.push(str)
    str = ""
  }
})
final.push(str)
console.log(final)

输出:

[
"test1,test2" ,
"test3,test4" ,
"test5"
]

答案 2 :(得分:-1)

使用正则表达式匹配一个非逗号,后跟最多8个字符,再跟另一个非逗号,并提前查找逗号或字符串结尾:

const input = 'test1,test2,test3,test4,test5';
console.log(
  input.match(/[^,].{0,8}[^,](?=,|$)/g)
);

由于在给定的输入中,test1,test2(以及多项的任何其他组合)的长度将为11或更大,因此将不包括在内。

如果您还希望允许长度为11,则将{0,8}更改为{0,9}

const input = 'test1,test2,test3,test4,test5';
console.log(
  input.match(/[^,].{0,9}[^,](?=,|$)/g)
);

如果可能存在长度为1的项目,请使非捕获组中第一个非逗号之后的所有内容都可选:

const input = 'test1,test2,test3,test4,t';
console.log(
  input.match(/[^,](?:.{0,9}[^,])?(?=,|$)/g)
);