Reputation: 7443
How can I split by space on sentences, but preserve newline (\n
) character as a separate word?
Input:
I am a sentence.\nBefore me, there is a newline. I would like this sentence to be the following:\n\n Look below
Output:
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'
Upvotes: 0
Views: 38
Reputation: 68933
You can try the following way:
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);
Upvotes: 1
Reputation: 10157
You could add spaces after and before the newline:
const newString = oldString.replace(/\n/g, ' \n ');
And then split by spaces:
const result = newString.split(' ');
Upvotes: 2