How to Remove all Line Breaks from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Remove all Line Breaks from a String in JavaScript #

Use the String.replace() method to remove all line breaks from a string, e.g. str.replace(/[\r\n]/gm, '');. The replace() method will remove all line breaks from the string by replacing them with an empty string.

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 passed a regular expression to the String.replace method.

The forward slashes / / mark the beginning and end of the regular expression.

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

The g (global) flag is used to specify that we want to match all occurrences of the regex, and not just the first occurrence.

The m (multiline) flag is used to specify that we want to match occurrences over multiple lines.

The square brackets [] are called a character class and are used to match either of the characters between the brackets.

We want to replace both \r and \n because 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 passed to the String.replace method is the replacement for each match.

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 !

For our purposes, we replace each occurrence of a line break with an empty string.

The String.replace() method doesn't mutate the original string, it returns a new string. Strings are immutable in JavaScript.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.