通过添加break重新格式化javascript中的字符串

reformatting a string in javascript by adding break ?

本文关键字:javascript 字符串 格式化 添加 break      更新时间:2023-09-26

我正在尝试用javascript创建一个函数,该函数将一个文本字符串作为参数,然后通过在字符串中添加'n来格式化它,这将形成段落。

  • 每个段落的长度只能是32个字符
  • 当我进入下一段时,我必须确保单词不会被切成两半。"

示例字符串:

"If we listened to our intellect, we'd never have a love affair. We'd never have a friendship. We'd never go into business, because we'd be cynical. Well, that's nonsense. You've got to jump off cliffs all the time and build your wings on the way down."

后格式应该像:

If we listened to our intellect, 'n
we'd never have a love affair. 'n
We'd never have a friendship.'n
We'd never go into business, 'n
because we'd be cynical. Well, 'n
that's nonsense. You've got to  'n
jump off cliffs all the time and 'n
build your wings on the way down"

我不确定我将如何处理这个问题,我也不希望有人能解决整个解决方案,我只想要一个起点,我在如何处理空格和单词以及何时将插入字符串方面遇到了困难。

这里有一个适合您的算法:

take your string; chop it up in two pieces: left (first 32 chars), right (the rest)
while right != empty
 if length(left) == 32
    while last character of left != space
       take last char off of left, prepend it to right
 print left
 new left = first 32 chars of right; right = rest
end while

您可以做一个简单的循环跟踪,跟踪自上一个换行符以来(或自第一行的文本开始以来)遇到的字符数。一旦该值超过32,则迭代回第一个空间,并将其替换为'n。想想如果一个单词超过32个字符该怎么办。

以下正则表达式对我有效:

str.match(/.{1,32}('s+|$)/g).join("'n");

演示:http://jsfiddle.net/PZxNK/