How to Remove all Line Breaks from a String in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20211 min read

Remove all Line Breaks from a String in JavaScript #

To remove all line breaks from a string, call the replace() method on the string, passing it a regular expression that replaces all occurrences of the \r and \n characters with an empty string. The replace method returns a new string with the matched characters replaced.

index.js
const str = 'a\n multi \n line \r string \n!'; const withoutLineBreaks = str.replace(/[\r\n]/gm, ''); console.log(withoutLineBreaks); // ๐Ÿ‘‰๏ธ a multi line string !

We have passed a regular expression to the String.replace method.

Let's first cover the g and m flags at the end of the regex.

With the g (global) flag we specify that we want to match all occurrences of the regex, not just the first one.

With the m (multiline) flag we specify that we want to match occurrences over multiple lines.

The [\r\n] part is a "character class" and is used to match either one of the characters between the square brackets.

We want to replace both \r and \n, because the line breaks vary depending on the operating system.

For example Windows uses \r\n as end of line character, whereas \n is the default in Unix.

The second parameter we pass to the String.replace method is the replacement for the matched characters, in our case an empty string.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee