How To Remove All Line Breaks From A String In JavaScript

remove all line breaks from a string in JavaScript

This tutorial will show you how to remove all line breaks from a string in JavaScript. This instruction uses three methods: for loopreplace(), and replaceAll().

Remove all Line Breaks from a String in JavaScript

Method 1: Using a for loop

We will have a for loop going through our string. If the characters are not lined breaks, we will copy them into a new string.

Completed code sample: 

var oldString = 'Welcome\n everyone \nto \rLearnShareIT.com \n!';
var newString = '';

for( var i = 0; i < oldString.length; i++ ) 
    if( !(oldString[i] === '\n' || oldString[i] === '\r') )
        newString += oldString[i];

console.log('This is the old string:', oldString);
console.log('This is the new string:', newString);

Output:

This is the old string:
Welcome
 everyone 
 to 
 LearnShareIT.com 
!

This is the new string:
Welcome everyone to LearnShareIT.com !

Method 2: Using replace()

String.replace(): search the string for a value and return a new string with that value replaced.

Syntax: 

string.replace(searchValue, newValue)
  • searchValue: the value to be searched for
  • newValue: the value to be replaced with

Example: 

var myString = 'Today is a beautiful day in Florida';
var newString = myString.replace('beautiful', 'bad');

console.log(myString);
console.log(newString); 

Output:

Today is a beautiful day in Florida
Today is a bad day in Florida

Let’s apply string.replace() to remove line breaks from our string: 

var oldString = 'Hello \nand \rwelcome \nto \nLearnShareIt.com \r!';
var newString = oldString.replace(/(\r\n|\n|\r)/gm, '');

console.log('This is the old string: ', oldString);
console.log('\n');
console.log('This is the new string: ', newString);

Output: 

This is the old string: 
Hello 
and 
welcome 
to 
LearnShareIt.com 
!

This is the new string: 
Hello and welcome to LearnShareIt.com !

Method 3: Using replaceAll()

Syntax

string.replaceAll(pattern, replacement)

The replaceAll() method replaces all occurrences of pattern and replaces it with replacement.

Let’s apply it to our problem: 

var myString = 'Welcome \neveryone \nto \nLearnShareIT.com \n!';
var newString = myString.replaceAll('\n', '');

console.log('This is the old string: ', myString);
console.log('\n');
console.log('This is the new string: ', newString); 

Output:

This is the old string: 
Welcome
everyone 
to 
LearnShareIT.com 
!

This is the new string: 
Welcome everyone to LearnShareIT.com !

Summary

Our tutorial has guided you through different ways to remove all Line Breaks from a String in JavaScript. We can use many methods like a simple for loop or powerful built-in methods like replace() and replaceAll().

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *