ekclone
ekclone

Reputation: 1092

Replace double new line character with only one?

How could I remove every double new line character with only one?

var string = "this is a ↵↵↵↵ test there will ↵↵ be more ↵↵↵↵ newline characters"

something like this

var string = "this is a ↵↵ test there will ↵ be more ↵↵ newline characters"

I've already tried this, but this replaces all new lines, i want to keep the single ones

string.replace(/[\n\n]/g, '')

Upvotes: 1

Views: 902

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

[\n\n] character class works as Logical OR. [\n\n] this means match \n or \n. what you need is \n followed by \n. So just remove the [] character class.

let str = `this is a 



test there will 

be more 



newline characters`

console.log(str.replace(/\n\n/g, '\n'))
console.log(str.replace(/\n+/g, '\n')) // <--- simply you can do this

Upvotes: 2

Sinisa Bobic
Sinisa Bobic

Reputation: 1311

string = string.replace(/\n{2}/g, '\n');

console.log(string);

That will do what you explained... but I believe you need this...

string = string.replace(/\n+/g, '\n');

console.log(string);

Upvotes: 2

Related Questions