The Wayback Machine - https://web.archive.org/web/20240624044904/https://www.geeksforgeeks.org/how-to-remove-all-line-breaks-from-a-string-using-javascript/
Open In App

How to remove all line breaks from a string using JavaScript?

Last Updated : 05 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

There are two methods to accomplish this task. One of the ways is by using a traditional programming loop and visiting every character one at a time. Another is using Regular Expressions.

Methods to Remove All Line Breaks from a String:

Using JavaScript slice and stitch methods

It is the basic way to realize the solution to this problem. Visit each character of the string and slice them in such a way that it removes the newline and carriage return characters.

Code snippet:

let newstr = "";
for (let i = 0; i < str.length; i++)
if (!(str[i] == "\n" || str[i] == "\r"))
newstr += str[i];

All this code snippet does is just 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.

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)

// 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

Using JavaScript RegEx with replace() method

Regular Expression:

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.

String.replace( regex / substr, replace with )

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

where g and m are for global and multiline flags.

The best part is that this method performed almost 10 times better than the previous one.

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

Using String.prototype.split() and Array.prototype.join()

Using String.prototype.split() and Array.prototype.join(), the 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.

Example: In this example The function removeLineBreaks() correctly eliminates all line breaks from the input string using split with a regular expression, then joins the substrings.

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?

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.

Example: This approach leverages template literals to define the input string, making it easier to handle multiline text. Then, the replace() method with a regular expression is used to remove all line breaks. The result is a clean string without any line breaks.

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

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

// Function to remove line breaks using ES6 template literals
function removeLineBreaksTemplateLiteral(str) {
    return str.replace(/[\r\n]+/gm, '');
}

// Function call
const newString = removeLineBreaksTemplateLiteral(str);
console.log("New String:", newString);

Output
Hello 
Welcome
to
GeeksForGeeks
New String: Hello WelcometoGeeksForGeeks

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.

Example: In this example, the removeLineBreaksReplaceAll function uses replaceAll() to replace all occurrences of \n, \r, and their combination with an empty string.

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

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

// Function to remove line breaks using replaceAll method
function removeLineBreaksReplaceAll(str) {
    return str.replaceAll('\r\n', '').replaceAll('\n', '').replaceAll('\r', '');
}

// Function call
const newString = removeLineBreaksReplaceAll(str);
console.log("New String:", newString);

Output
Hello 
Welcome
to
GeeksForGeeks
New String: Hello WelcometoGeeksForGeeks





Previous Article
Next Article

Similar Reads

How to remove line breaks from the string in PHP?
The line break can be removed from string by using str_replace() function. The str_replace() function is an inbuilt function in PHP which is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.Syntax: str_replace ( $search
2 min read
How to replace line breaks with br tag using JavaScript ?
In JavaScript, you can replace line breaks (\n or \r\n) with &lt;br&gt; tags in a string using different approaches. But before learning the approaches, let's see an example. Example: Input: `Geeks for Geeks is a computer science portal where people study computer science`Output: "Geeks for Geeks is &lt;br&gt; a computer science portal &lt;br&gt; w
2 min read
How to prevent line breaks in the list of items using CSS?
The display:inline-block property is used to show an element in the inline-level block container. It converts the block of elements into an inline element. Use height and width property to set an inline element. The display property is used to prevent a line break of a list of items. Syntax: element { display:inline-block;} Example: C/C++ Code &lt;
1 min read
How to add line breaks to an HTML textarea?
Way of implementing line breaks differ from one platform to another. The following approach takes input text from HTML Textarea and adds line breaks using JavaScript. Approach: This task can be achieved by using some predefined array and string functions provided by JavaScript. In the following code, the input from the textarea is processed by Java
1 min read
Bootstrap 5 Columns Breaks
Bootstrap 5 Columns are smaller cells or sections inside a row in a Grid System. The columns are placed beside one another until it exceeds the 12-column limit for each row. Column breaks are used if we manually want to push to the new line before or without exceeding the limit. There is no exact class that is used to make a break instead there is
2 min read
Different ways to add Breaks and Spaces in HTML.
In HTML, Breaks and Spaces can be added using various elements and entities. The &lt;br&gt; tag creates a line break, while &amp;nbsp; represents a non-breaking space. Additionally, the &lt;p&gt; tag defines a paragraph, creating space between blocks of text. CSS properties like margin and padding can also be used for more precise control over spac
1 min read
How to Read a File Line by Line using Node.js ?
The ability to Read a File Line by Line using Node allows us to read large files without entirely storing them in memory. It is useful in saving resources and improving the efficiency of the application. It allows us to look for the information that is required and once the relevant information is found, we can stop the search process and can preve
3 min read
How to remove all Non-ASCII characters from the string using JavaScript ?
In this article, we are given a string containing some non-ASCII characters and the task is to remove all non-ASCII characters from the given string. Approaches to remove all Non-ASCII Characters from String: Table of Content Using ASCII values in JavaScript regExUsing Unicode in JavaScript regExUsing ASCII values with the Array filter methodApproa
3 min read
Remove all occurrences of a character in a string using JavaScript
Removing all occurrences of a character in a string means eliminating every instance of a particular character from the given string, resulting in a modified string without that character. Approaches to Remove all occurrences of a character in a string using JavaScriptTable of Content Approach 1: Using a JavaScript Regular ExpressionApproach 2: Usi
3 min read
How to read a Large File Line by Line in PHP ?
We will use some file operations to read a large file line by line and display it. Read a file: We will read the file by using fopen() function. This function is used to read and open a file. Syntax: fopen("filename", access_mode); Parameter: filename: Filename is the name of the file access_mode: It is the mode of the file that includes r - read m
2 min read
three90RightbarBannerImg