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

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

In this posrt, you'll learn how to 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]; 

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

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

/\r\n|\n|\r/gm

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

/[\r\n]+/gm

where g and m are for global and multiline flags.

Code snippet:

function remove_linebreaks( var str ) { 
    return str.replace( /[\r\n]+/gm, "" ); 
} 

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

Example:

<!DOCTYPE html> 
<html> 

<head> 
    <title> 
        Remove all line breaks from 
        a string using JavaScript 
    </title> 

    <script> 
    // 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 = 
            document.getElementById('raw-text').value; 

        console.time(); 

        // For printing time taken on console. 
        document.getElementById('res-1').innerHTML
                = remove_linebreaks_ss( sample_str ); 
        console.timeEnd(); 

        console.time(); 
        document.getElementById('res-2').innerHTML
                = remove_linebreaks( sample_str); 
        console.timeEnd(); 
    } 
    </script> 
</head> 

<body> 
    <center> 
        <textarea id="raw-text"></textarea> 
        <br> 

        <button onclick="removeNewLines()"> 
            Remove Newlines 
        </button> 

        <h6>Method 1:</h6> 
        <p id='res-1'></p> 

        <h6>Method 2:</h6> 
        <p id='res-2'></p> 
    </center> 
</body> 

</html>                 

Output:

  • Before Clicking on the button: How to remove all line breaks from a string using JavaScript
  • After Clicking on the button: How to remove all line breaks from a string using JavaScript

javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Create a Line Through Effect with JavaScript

In this post we are going to create an amazing line through effect, with help of CSS and lots of JavaScript. So, head over to your terminal and create a folder LineThroughEffect. Create three files -index.html, main.js and styles.css inside it.

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.