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





Hi Guys,

In this example,I will learn you how to remove all line breaks from a string using can easy and simply remove all line breaks from a string using javascript.

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

Windows: \r\n carriage return followed by 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 traditional programming loop and visiting every character one at a time. Another is using Regular Expressions.

The slice and stitch method: 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:

var newstr = "";

for( var i = 0; i < str.length; i++ )

if( !(str[i] == '\n' || str[i] == '\r') )

newstr += str[i];

Regular Expression: This method uses regular expressions to detect and replace newlines in the string. It is fed into replace function along with 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


As you can see that this regex has covered all cases separated by | operator. This can be reduced to


where g and m are for global and multiline flags.

Code snippet:

function remove_linebreaks( var str ) {

return str.replace( /[\r\n]+/gm, "" );



<!DOCTYPE html>




Remove all line breaks from

a string using JavaScript



// Method 1

// Slice and Stitch

function remove_linebreaks_ss( str ) {

var newstr = "";

for( var i = 0; i < str.length; i++ )

if( !(str[i] == '\n' || str[i] == '\r') )

newstr += str[i];

return newstr;


// Method 2

// Regular Expression

function remove_linebreaks( str ) {

return str.replace( /[\r\n]+/gm, "" );


function removeNewLines() {

var sample_str =



// For printing time taken on console.


= remove_linebreaks_ss( sample_str );




= remove_linebreaks( sample_str);







<textarea id="raw-text"></textarea>


<button onclick="removeNewLines()">

Remove Newlines


<h6>Method 1:</h6>

<p id='res-1'></p>

<h6>Method 2:</h6>

<p id='res-2'></p>




It will help you...