我发现的大多数自动换行功能都绑定到 css 和/或浏览器 dom。我正在 javascript 环境(rhino)中工作,需要找到或设计一个更好的自动换行,该换行可以在给定行长度值之前的空白处中断。我当前的解决方案只是搜索给定字符之前的最后一个空格,然后剪切左侧,将其存储为一行输出(在数组返回中)。重复此操作,直到不再有文字为止。
希望有人看到一些优雅的东西。
你可以这样写:
let wordwrapped = (original + ' ').replace(/(\S(.{0,78}\S)?)\s+/g, '$1\n').trim();
Run Code Online (Sandbox Code Playgroud)
这将替换\s+为\n至少一个、最多八十个、最好是尽可能多的字符。(注意:如果一行中的字符超过八十个且没有空格,则前后会有换行,但内部不会换行。)
看看它的实际效果:
let wordwrapped = (original + ' ').replace(/(\S(.{0,78}\S)?)\s+/g, '$1\n').trim();
Run Code Online (Sandbox Code Playgroud)
// 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;Run Code Online (Sandbox Code Playgroud)
此正则表达式将包装每个 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);
}
Run Code Online (Sandbox Code Playgroud)
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));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4045 次 |
| 最近记录: |