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:
Table of Content
Method 1: 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.
// 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); |
Hello Welcome to GeeksForGeeks new string : Hello Welcome to GeeksForGeeks
Method 2: 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.
// 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(); |
Hello Welcome to GeeksForGeeks nwe String: Hello Welcome to GeeksForGeeks