gpt4 book ai didi

javascript - 在不破坏单词的情况下在 Javascript 中分块/拆分字符串

转载 作者:可可西里 更新时间:2023-11-01 02:54:50 24 4
gpt4 key购买 nike

你好,

我想知道是否有一种简单的方法可以在不破坏单词的情况下分块/拆分字符串。

例如:

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);
}

但我真的怀疑我能否修改它,以免单词被分成两半。有什么建议吗?

谢谢!

最佳答案

这里有一些蛮力代码可以做到这一点:

function splitIntoLines(input, len) {
var i;
var output = [];
var lineSoFar = "";
var temp;
var words = input.split(' ');
for (i = 0; i < words.length;) {
// check if adding this word would exceed the len
temp = addWordOntoLine(lineSoFar, words[i]);
if (temp.length > len) {
if (lineSoFar.length == 0) {
lineSoFar = temp; // force to put at least one word in each line
i++; // skip past this word now
}
output.push(lineSoFar); // put line into output
lineSoFar = ""; // init back to empty
} else {
lineSoFar = temp; // take the new word
i++; // skip past this word now
}
}
if (lineSoFar.length > 0) {
output.push(lineSoFar);
}
return(output);
}

function addWordOntoLine(line, word) {
if (line.length != 0) {
line += " ";
}
return(line += word);
}

如果这个例程遇到一个比所需行长更长的单词,它会把它自己放在一行上,不会将其打散。

你可以在这里玩:http://jsfiddle.net/jfriend00/fbaLe/

关于javascript - 在不破坏单词的情况下在 Javascript 中分块/拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6632530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com