Open In App

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

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
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.

JavaScript
// Input string
str = "Hello \nWelcome\nto\nGeeksForGeeks";

// Display Input string
console.log(str);

// Regular Expression
function remove_linebreaks(str) {
    return str.replace(/[\r\n]+/gm, " ");
}
function removeNewLines() {
    let sample_str = str;

    // For printing time taken on console.
    console.log("nwe String: " + remove_linebreaks(str));
}

removeNewLines();

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.

JavaScript
// Input string
str = "Hello \nWelcome \nto \nGeeksForGeeks"

// Display Input string
console.log(str)

// Function to remove line breaks
function remove_linebreaks_ss(str) {
    let newstr = "";
    
    // Looop and traverse string
    for (let i = 0; i < str.length; i++)
        if (!(str[i] == "\n" || str[i] == "\r"))
            newstr += str[i];
    console.log("new string : "+newstr);
}

// Function call
remove_linebreaks_ss(str);

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.

JavaScript
function removeLineBreaks(str) {
  return str.split(/\r?\n|\r/).join('');
}

const stringWithLineBreaks = 
    "Hello\nworld!\nHow are\nyou?";
const stringWithoutLineBreaks = 
    removeLineBreaks(stringWithLineBreaks);
console.log(stringWithoutLineBreaks); 

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.

JavaScript
// Input string
const str = `Hello 
Welcome
to
GeeksForGeeks`;

// Display Input string
console.log(str);

// Function call
const newString = str.replace(/[\r\n]+/gm, '');
console.log("New String:", newString);

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.

JavaScript
// Input string
const str = `Hello 
Welcome
to
GeeksForGeeks`;

// Display Input string
console.log(str);


// Function call
const newString = str.replaceAll('\r\n', '').replaceAll('\n', '').replaceAll('\r', '');
console.log("New String:", newString);

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.

JavaScript
let str = "Hello,\nWorld!\r\nThis is a\rtest.";
let result = str.split(/[\r\n]+/).filter(Boolean).join('');
console.log(result); 

Output
Hello,World!This is atest.


Next Article

Similar Reads