如何在句子上按空格分开,但将换行符(\n)保留为单独的单词?

输入:

I am a sentence.\nBefore me, there is a newline. I would like this sentence to be the following:\n\n Look below


输出:

Array: ['I', 'am', 'a', 'sentence.', '\n', 'Before', 'me,', 'there', 'is', 'a', 'newline.', 'I', 'would', 'like', 'this', 'sentence', 'to', 'be', 'the', 'following:', '\n', '\n', 'Look', 'below'

最佳答案

您可以尝试以下方式:



var str = `I am a sentence.\nBefore me, there is a newline. I would like this sentence to be the following:\nLook below`;

var res = str.split(/ |(\n)/g).filter(i => i);
console.log(res);

10-06 05:27
查看更多