Reputation: 853
Let's say I have string like this:
Hello, \n\r \n\n\n \n World \n\n !
and I want it to look like this:
Hello,
World
!
So anytime there are two or more adjacent newline characters or newline character adjacent to single or more whitespaces, it should replace them with single newline character.
How to achieve this in JavaScript?
Upvotes: 0
Views: 397
Reputation: 215137
You can use /(?: *[\n\r])+ */
:
*[\n\r]
matches literal white space followed by a new line character;+
to match one or more consecutive whitespace + new line characters;*
to match zero or more white spaces at the end of pattern;var s = "Hello, \n\r \n\n\n \n World \n\n ! \n A new line";
console.log(s);
console.log(s.replace(/(?: *[\n\r])+ */g, '\n'));
Upvotes: 1