作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将文本自动换行到最大长度为 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/
我是一名优秀的程序员,十分优秀!