Remove all line breaks from a JavaScript string?

Answered
nick asked this question 8 months ago
nick on Dec 5, 2021

I often have strings that contain line break characters \n.

How can I take a string and remove all of those characters from it?

2 suggested answers
itsbambi on Dec 7, 2021

Using replace() with a regular expression should do the trick:

string.replace(/(\r\n|\n|\r)/gm, "")

That regular expression will remove all instances of \r\n, \n, or \r in your string.

Those three versions will cover different encodings for Windows (\r\n), Linux (\n), and Apple (\r) operating systems.

0 replies
looper003 on Dec 7, 2021 · Edited

You can remove just instances of \n line breaks in your string with this:

let string = "Your string goes like this.\n\n"

string = string.replace(/\n/gm, "")

// string = "Your string goes like this."
0 replies
Answered