简体   繁体   English

空白上的仅 Javascript 自动换行功能?

[英]Javascript-only wordwrap function on whitespace?

Most wordwrap functions I've found are bound to css and/or a browser dom.我发现的大多数自动换行功能都绑定到 css 和/或浏览器 dom。 I'm working in a javascript environment (rhino) and need to find or design a better word wrap that breaks on whitespace before a given line length value.我在 javascript 环境 (rhino) 中工作,需要找到或设计一个更好的自动换行,在给定的行长度值之前中断空格。 My current solution just searches for the last white space before the given character, then clips the left side, storing it as a line of output (in an array return).我当前的解决方案只是搜索给定字符之前的最后一个空格,然后剪辑左侧,将其存储为一行输出(在数组返回中)。 Repeat until no more text remains.重复直到没有更多的文字。

Hoping someone has seen something elegant.希望有人看到了一些优雅的东西。

You could write something like:你可以这样写:

let wordwrapped = (original + ' ').replace(/(\S(.{0,78}\S)?)\s+/g, '$1\n').trim();

That will replace \\s+ with \\n after at-least-one,-at-most-eighty,-preferably-as-many-as-possible characters.这将在至少一个,最多八十个,最好是尽可能多的字符之后用\\n替换\\s+ (Note: if there are more than eighty characters in a row without whitespace, then there will be a line-break before and after them, but no wrapping will take place inside them.) (注意:如果一行中没有空格的字符超过八十个,那么它们前后会有一个换行符,但它们内部不会发生换行。)

See it in action:看看它在行动:

 // 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>

This regex will wrap every 0-width character and respect whitespaces and hyphens also cuts words longer than width characters.此正则表达式将包装每个 0 宽度字符并尊重空格,连字符也会切割比宽度字符长的单词。 Try it out on regexr .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));

RegEx is really the way to go.正则表达式真的是要走的路。 /.{0,79}(?:\\s|$)/g will grab the longest line under 80 characters ending with a character or the end of the file. /.{0,79}(?:\\s|$)/g将抓取 80 个字符以下的最长行,以一个字符或文件结尾结尾。 Calling exec multiple times will extract each line.多次调用exec将提取每一行。

var text = "";
var regex = /.{0,79}(?:\s|$)/g;
var lines = [];
var line;

while (line = regex.exec(text)) {
    lines.push(line);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM