gpt4 book ai didi

javascript - 如何将文本自动换行到给定的行长度(以字符为单位)?

转载 作者:行者123 更新时间:2023-12-03 07:54:20 27 4
gpt4 key购买 nike

我想将文本自动换行到最大长度为 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

最佳答案

您可以使用正则表达式 (?=\S).{0,99}\S(?!\S)|\S{100}.matchAll 结合使用找到所需的符号 block (参数等于 100)。

这里正则表达式匹配:

  • (?=\S).{0,99}\S(?!\S) 一到一百个符号的 block ,以非空白符号开头和结尾,后跟空格或行尾:
    • (?=\S) 环视检查第一个符号是否为非空格,
    • .{0,99} 0 到 99 之间的任何符号(换行符除外),
    • \S 匹配最后一个非空白符号,
    • (?!\S) 检查匹配项后面是否有空格符号(以防止在单词中间换行)
  • \S{100} 一百个后续非空白符号:对于非常长的单词,跨越最大预期行长度。

代码示例:

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.`

console.log(wrapLines(sentence, 100));

function wrapLines(str, maxLen){
let reg = new RegExp('(?=\\S).{0,'+(maxLen-1)+'}\\S(?!\\S)|\\S{'+maxLen+'}', 'gm')
console.log(reg)
return Array.from(str.matchAll(reg), (m) => m[0]);
}

关于javascript - 如何将文本自动换行到给定的行长度(以字符为单位)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76433136/

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