gpt4 book ai didi

空格上的仅 Javascript wordwrap 函数?

转载 作者:行者123 更新时间:2023-11-29 10:50:13 25 4
gpt4 key购买 nike

我发现的大多数自动换行功能都绑定(bind)到 css 和/或浏览器 dom。我在 javascript 环境 (rhino) 中工作,需要找到或设计一个更好的自动换行,在给定行长度值之前的空白处中断。我当前的解决方案只是搜索给定字符之前的最后一个空格,然后剪辑左侧,将其存储为一行输出(在数组返回中)。重复直到没有更多的文本。

希望有人看到了一些优雅的东西。

最佳答案

你可以这样写:

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

这将在至少一个,最多八十个,最好尽可能多的字符之后用 \n 替换 \s+ . (注意:如果一行超过八十个字符没有空格,则前后换行,但内部不换行。)

查看实际效果:

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

关于空格上的仅 Javascript wordwrap 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11675397/

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