Open In App

JavaScript - How to Remove All Line Breaks From a String?

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

Here are different ways to remove all line breakes from a string in JavaScript.

1. Using JavaScript RegEx with replace() Method

This method uses regular expressions to detect and replace newlines in the string. It is fed into replace function along with a string to replace with, which in our case is an empty string.

  • The regular expression to cover all types of newlines is:
/\r\n|\n|\r/gm
  • As you can see that this regex has covered all cases separated by the | operator. This can be reduced to:
/[\r\n]+/gm

Example: This example shows the removal of all line breaks from the given string.


Output
Hello 
Welcome
to
GeeksForGeeks
nwe String: Hello  Welcome to GeeksForGeeks

Line breaks in strings vary from platform to platform, but the most common ones are the following:

  • Windows: \r\n carriage return followed by a newline character.
  • Linux: \n just a newline character.
  • Older Macs: \r just a carriage return character.

2. Using JavaScript slice() Method

We will visit each character of the string and slice them in such a way that it removes the newline and carriage return characters. We will copy all the characters that are not "newline" or "carriage return" to another variable. However, there are a lot of overheads in this solution, and therefore not an optimal way to remove newlines.


Output
Hello 
Welcome 
to 
GeeksForGeeks
new string : Hello Welcome to GeeksForGeeks

3. Using String split() and Array join() Methods

In this approach, splits the string by line breaks using a regular expression. Then, it joins the resulting array elements back into a single string, effectively removing all line breaks.


Output
Helloworld!How areyou?

4. Using ES6 Template Literals with replace() method

ES6 introduced template literals which offer a convenient way to work with multiline strings. You can utilize template literals along with the replace() method to remove line breaks efficiently.


Output
Hello 
Welcome
to
GeeksForGeeks
New String: Hello WelcometoGeeksForGeeks

5. Using JavaScript replaceAll() method

The replaceAll() method allows for replacing all instances of a substring or pattern in a string. This approach is straightforward and efficient for removing line breaks.


Output
Hello 
Welcome
to
GeeksForGeeks
New String: Hello WelcometoGeeksForGeeks

6. Using filter() with split() Method

Another efficient way to remove all line breaks from a string is by using the split() method to break the string into an array based on line breaks, then using the filter() method to remove any empty elements and finally, join() to concatenate the filtered elements back into a single string.


Output
Hello,World!This is atest.

Next Article

Similar Reads