美好的一天,
我想知道是否有一种简单的方法可以在不破坏单词的情况下对字符串进行分块/分割.
例如:
var input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin placerat, nisi nec vulputate scelerisque, metus lectus ultricies massa, et luctus elit libero eu erat. Fusce vitae sem lacus, eu ullamcorper lectus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
如果我以80个字符长的长度中断,应该返回这样的数组:
var output = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin placerat, nisi",
"nec vulputate scelerisque, metus lectus ultricies massa, et luctus elit libero",
"eu erat. Fusce vitae sem lacus, eu ullamcorper lectus. Lorem ipsum dolor sit",
"amet, consectetur adipiscing elit."];
我发现了一段非常不错的代码:
//http://phpjs.org/functions/chunk_split:369
function chunk_split (body, chunklen, end) {
// Returns split line
//
// version: 1103.1210
// discuss at: http://phpjs.org/functions/chunk_split
// + original by: Paulo Freitas
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Theriault
// * example 1: chunk_split('Hello world!', 1, '*');
// * returns 1: 'H*e*l*l*o* *w*o*r*l*d*!*'
// * example 2: chunk_split('Hello world!', 10, '*');
// * returns 2: 'Hello worl*d!*'
chunklen = parseInt(chunklen, 10) || 76;
end = end || '\r\n';
if (chunklen < 1) {
return false;
}
return body.match(new RegExp(".{0," + chunklen + "}", "g")).join(end);
}
但是我真的怀疑我是否可以修改它,以确保单词不会被分成两半.有小费吗?
谢谢!
解决方法:
像这样吗
var n = 80;
while (n) {
if (input[n++] == ' ') {
break;
}
}
output = input.substring(0,n).split(' ');
console.log(output);
更新
现在,我重新阅读了问题,这是一个更新的解决方案:
var len = 80;
var curr = len;
var prev = 0;
output = [];
while (input[curr]) {
if (input[curr++] == ' ') {
output.push(input.substring(prev,curr));
prev = curr;
curr += len;
}
}
output.push(input.substr(prev));
标签:javascript,string
来源: https://codeday.me/bug/20191010/1887621.html