How to remove all line breaks from a string using JavaScript?
Last Updated :
05 Jun, 2024
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:
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);
OutputHello
Welcome
to
GeeksForGeeks
new string : Hello Welcome to GeeksForGeeks
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();
OutputHello
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);
OutputHelloworld!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);
OutputHello
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);
OutputHello
Welcome
to
GeeksForGeeks
New String: Hello WelcometoGeeksForGeeks
Please Login to comment...