我想文字 Package 成一个数组的行(短语/行)与N个字符的最大长度的文本。如果一个单词大于最大行长度,则该单词应被剪切到该长度。
编辑:n个字符的最大长度永远不会小于100个字符,我用了10个字符来向你展示我的代码无法正常工作
const sentence =`Wake has three meanings as a noun, and, yes, just about as many meanings as a verb! So get set. To wake is come out of sleep, a verb you'll recognize from "Wake up! You're asleep at the wheel!" You can wake feelings, as well as the people who are having them. The wake before the funeral caused Mike to wake from his depression and decide to live life to the fullest. His first act was to water ski; he eventually mastered staying upright while crossing the wake of the boat that was towing him.`
// shorten with max characters of 10
console.log(shorten(sentence, 10));
function shorten(str, maxLen) {
if(str.length <= maxLen) return [str];
let max, min = 0, i = 1;
const result = [];
while (maxLen * i < str.length) {
max = str.lastIndexOf(' ', maxLen * i);
result.push(str.substr(min, max));
min = max + 1;
i++;
}
return result;
}
问题是我的代码不能像你看到的那样正常工作。
所需输出为:
["Wake has", "three", "meanings", "as a noun,", ...] // each one has length of : 8 - 5 - 8 - 10
4条答案
按热度按时间b5buobof1#
您可以将regex
(?=\S).{0,99}\S(?!\S)|\S{100}
与.matchAll结合使用,以查找所需的符号块(参数等于100)。这里正则表达式匹配:
(?=\S).{0,99}\S(?!\S)
一个到一百个符号的块,以非空白符号开始和结束,后跟空白或行尾:(?=\S)
检查第一个符号是否为非空白,.{0,99}
0到99之间的任何符号,除换行符外,\S
将最后一个符号匹配为非空白,(?!\S)
检查匹配后是否有空格符号(以防止在单词中间换行)\S{100}
一百个后续非空白符号:对于非常长的字的情况,其跨越最大预期行长度。代码示例:
1hdlvixo2#
据我所知,这项任务是用等宽字体对文本进行自动换行。
不知何故,它的工作:
3htmauhk3#
改成
bwleehnv4#
你可以这样做,如果你没有大量的文本,这可能是可行的:
这是未经测试的代码,我希望你在某些地方需要+1或-1,但这是一个例子。
(If有人想调整它并修复它,请随意这样做)。