私は文字列を持っています:
"This is the\nstring with\nline breaks\n"
私は取得する必要があります:
[This, is, the\n, string, with\n, line, breaks\n
]
.split(/ \ s {1、} /)を使用すると、\n改行が消えます。それらを保存する方法は?
複数のスペースを考慮する必要があります
私は文字列を持っています:
"This is the\nstring with\nline breaks\n"
私は取得する必要があります:
[This, is, the\n, string, with\n, line, breaks\n
]
.split(/ \ s {1、} /)を使用すると、\n改行が消えます。それらを保存する方法は?
複数のスペースを考慮する必要があります
おそらく、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つ以上)を意味します。
分割をキャプチャグループにすることで、結果の配列に表示されます。その後、それをマッサージすることができます:
"This is the\nstring with\nline breaks\n".split(/(\s+)/);
結果:
["This", " ", "is", " ", "the", "\n", "string", " ", "with", "\n", "line", " ",
"breaks", "\n", ""]
この配列を操作すると、要求された結果が生成されるので、演習として残しておきます。
代わりにこれを使用してください:
.split(/ +/); // (/ +/ to take multiple spaces into account.)
なぜなら:
"This is the\nstring with\nline breaks\n".split(' ');
戻り値:
["This", "is", "the
string", "with
line", "breaks
"]
"\n"
これらの文字列は、コンソールでは代わりに実際の改行としてレンダリングされるため、文字通り表示されない場合があります。
スペースで簡単に分割
.split(" ");