javascript - 如何将字符串分成小于定义长度的部分
问题描述
我有一个字符串 ( this is the very very very very long string
),我想要将它分成少于 25 个字符的部分,并且这些部分必须有完整的单词,例如:
this is the very very
而very very long string
不是this is the very very ver
and y very long string
。
解决方案
连接和收集这些部分并确实限制每个部分的连接长度的reduce
基于方法可以实现类似于下一个提供的示例代码......
function concatAndCollectPartialsOfLimitedLength(collector, str) {
const { limit = 24, list } = collector;
const lastIdx = list.length - 1;
const partial = list[lastIdx];
if (partial && (partial.length + str.length + 1 <= limit)) {
// concatenate if partial exists and if the length of its
// next concatenated version does not exceed the limit ...
list[lastIdx] = [partial, str].join(' ');
} else {
// ... otherwise provide and collect the base
// for the following concatenation step(s).
list.push(str);
}
return collector;
}
console.log(
'concatenated partial length is limited to 24 chars ...',
"this is the very very very very long string and some more of it and even more"
.trim()
.split(/\s+/)
.reduce(concatAndCollectPartialsOfLimitedLength, { list: [] })
.list
);
console.log(
'concatenated partial length is limited to 13 chars ...',
"this is the very very very very long string and some more of it and even more"
.trim()
.split(/\s+/)
.reduce(
concatAndCollectPartialsOfLimitedLength,
{ limit: 13, list: [] }
)
.list
);
console.log(
'concatenated partial length is limited to 31 chars ...',
"this is the very very very very long string and some more of it and even more"
.trim()
.split(/\s+/)
.reduce(
concatAndCollectPartialsOfLimitedLength,
{ limit: 31, list: [] }
)
.list
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
推荐阅读
- bash - SQLITE3 从导入中排除 - 表中已经存在的数据行 - 不使用主键
- python - 部署到heroku(Django项目)后,Pandas数据框未按预期运行
- python - 如何使用 for 循环简化此字典创建
- javascript - 如何在异步 api 请求后重新路由我的反应应用程序
- javascript - 在矩阵的第 N 列中查找最大/最小元素索引的快速方法
- python - 在 Mac 上运行 Tkinter
- amazon-s3 - Sentry 不会将 DSYM 文件上传到 S3 文件存储后端并给我异常:NoSuchKey: An error occurred (NoSuchKey)
- swift - 如何在 iOS 13 上以编程方式更改顶部栏背景 swift 4
- jmeter - 如何发送 RFH2 格式的消息?
- python - Python:如何检查日期是否不明确?