kecman
kecman

Reputation: 853

How to remove all adjacent newlines and whitespaces in Javascript and replace them with single newline?

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

Answers (1)

akuiper
akuiper

Reputation: 215137

You can use /(?: *[\n\r])+ */:

  • *[\n\r] matches literal white space followed by a new line character;
  • use + to match one or more consecutive whitespace + new line characters;
  • use * 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

Related Questions