微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

由长度小于16的数组字符串组成

如何解决由长度小于16的数组字符串组成

我有这个数组["Brad","came","to","dinner","with","us"]

Brad came to dinner with us(27个字符> 16),因此我需要将其分成2个字符串:

Brad came to
dinner with us

无法切片单词

let inpt=["Brad","us"]
op=[]
for(i of inpt) if (op.join('').length+i.length <16) {op.push(i)} else break
console.log(op.join(' '))

这让我得到了第一部分,但是如果我的输入数组(字符串)长于16 + 16 + 16...。

解决方法

以空格连接后,使用正则表达式匹配最多16个字符,后跟一个空格或字符串的结尾:

let inpt=["Brad","came","to","dinner","with","us"];
const str = inpt.join(' ');
const matches = str.match(/.{1,16}(?: |$)/g);
console.log(matches);

,

也可以通过Array.reduce完成:

let inpt=["Brad","us"];

let out = inpt.reduce((acc,el) => {
  let l = acc.length;
  if (l === 0 || (acc[l - 1] + el).length > 15) {
    acc[l] = el;
  } else {
    acc[l - 1] += " " + el;
  }
  return acc;
},[]);

console.log(out);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。