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

最後の改行文字以降(または最初の行のテキストの先頭以降)に出会った文字数を追跡するために、単純なサイクルを実行できます。この値が32を超えたら、最初のスペースに戻って繰り返し、それを。に置き換え\nます。単語が32文字を超える場合の対処方法を考えてください。

于 2013-02-04T14:44:24.410 に答える
0

次の正規表現は私のために働いた:

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

デモ:http: //jsfiddle.net/PZxNK/

于 2013-02-04T14:52:00.520 に答える