我发现的大多数自动换行函数都绑定到 css 和/或浏览器 dom。我在 javascript 环境 (rhino) 中工作,需要找到或设计一个更好的自动换行,在给定的行长值之前打破空白。我当前的解决方案只是搜索给定字符之前的最后一个空格,然后剪切左侧,将其存储为一行输出(在数组返回中)。重复直到没有更多的文本。
希望有人看到优雅的东西。
我发现的大多数自动换行函数都绑定到 css 和/或浏览器 dom。我在 javascript 环境 (rhino) 中工作,需要找到或设计一个更好的自动换行,在给定的行长值之前打破空白。我当前的解决方案只是搜索给定字符之前的最后一个空格,然后剪切左侧,将其存储为一行输出(在数组返回中)。重复直到没有更多的文本。
希望有人看到优雅的东西。
你可以这样写:
let wordwrapped = (original + ' ').replace(/(\S(.{0,78}\S)?)\s+/g, '$1\n').trim();
这将替换\s+
为\n
至少一个,最多八十个,最好是尽可能多的字符。(注意:如果一行中没有空格的字符超过 80 个,那么它们之前和之后会有一个换行符,但它们内部不会发生换行。)
看看它的实际效果:
// generate random sequence of 500 letters and spaces:
let original = String.fromCharCode.apply(String, Array.from({length: 500}, () => 64 + Math.floor(Math.random() * 27))).replace(/@/g, ' ');
// perform word-wrapping:
let wordwrapped = (original + ' ').replace(/(\S(.{0,78}\S)?)\s+/g, '$1\n').trim();
// show the results in the <pre> elements:
document.getElementById('ruakh-original').innerText = 'original:\n' + original;
document.getElementById('ruakh-word-wrapped').innerText = 'word-wrapped:\n' + wordwrapped;
<pre id="ruakh-original"></pre>
<pre id="ruakh-word-wrapped"></pre>
此正则表达式将包装每个 0 宽度字符并尊重空格和连字符也会切割比宽度字符更长的单词。在regexr上尝试一下。
/**
* Wrap every 0-`width` character and respect whitespaces and hyphens also cuts words longer than `width` characters.
* @param str The string to wrapped
* @param width The maximum length a string can be
*/
function wordwrap(str, width) {
return str.replace(new RegExp(`(?:\\S(?:.{0,${width}}\\S)?(?:\\s+|-|$)|(?:\\S{${width}}))`, 'g'), s => `${s}\n`).slice(0, -1);
}
function wordwrap(str, width) {
return str.replace(new RegExp('(?:\\S(?:.{0,' + width + '}\\S)?(?:\\s+|-|$)|(?:\\S{' + width + '}))', 'g'), function (s) {return s + '\n'}).slice(0, -1);
}
console.log(wordwrap('This is my regular-expression. It will wrap every 0-20 character and respect whitespaces and hyphens, also cuts reallylongwordslikethis.', 20));
正则表达式确实是要走的路。/.{0,79}(?:\s|$)/g
将抓取以字符或文件结尾结尾的 80 个字符以下的最长行。exec
多次调用将提取每一行。
var text = "";
var regex = /.{0,79}(?:\s|$)/g;
var lines = [];
var line;
while (line = regex.exec(text)) {
lines.push(line);
}