0

私は文字列を持っています:

"This is the\nstring with\nline breaks\n"

私は取得する必要があります:

[This, is, the\n, string, with\n, line, breaks\n]

.split(/ \ s {1、} /)を使用すると、\n改行が消えます。それらを保存する方法は?

複数のスペースを考慮する必要があります

4

4 に答える 4

3

おそらく、matchあなたが望むものをあなたに与えるでしょう

"This is the\nstring with\nline breaks\n".match( /([^\s]+\n*|\n+)/g );

// ["This", "is", "the\n", "string", "with\n", "line", "breaks\n"]

[^\s]+は、可能な限り多くの非スペース(1つ以上)を
\n*意味し、可能な限り多くの新しい行(0以上)を
|意味し、 OR\n+意味し、可能な限り多くの新しい行(1つ以上)を意味します。

于 2012-11-29T12:29:56.360 に答える
1

分割をキャプチャグループにすることで、結果の配列に表示されます。その後、それをマッサージすることができます:

 "This is the\nstring with\nline breaks\n".split(/(\s+)/);

結果:

["This", " ", "is", " ", "the", "\n", "string", " ", "with", "\n", "line", " ", 
 "breaks", "\n", ""]

この配列を操作すると、要求された結果が生成されるので、演習として残しておきます。

于 2012-11-29T12:38:09.017 に答える
0

代わりにこれを使用してください:

.split(/ +/); // (/ +/ to take multiple spaces into account.)

なぜなら:

"This is the\nstring with\nline breaks\n".split(' ');

戻り値:

["This", "is", "the
string", "with
line", "breaks
"]

"\n"これらの文字列は、コンソールでは代わりに実際の改行としてレンダリングされるため、文字通り表示されない場合があります。

于 2012-11-29T12:24:16.860 に答える
0

スペースで簡単に分割

.split(" ");
于 2012-11-29T12:24:56.637 に答える