0

我正在尝试在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"

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

4

3 回答 3

3

这里有一个算法给你:

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
于 2013-02-04T14:45:51.023 回答
0

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

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

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

于 2013-02-04T14:52:00.520 回答
0

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

于 2013-02-04T14:44:24.410 回答