How to remove all line breaks and whitespace in JavaScript

JavaScript remove line breaks and whitespace example; In this tutorial you will learn how to remove all Line Breaks from a String in JavaScript.

In Javascript we can use the String.replace() method to remove all line breaks from a string. The replace() method will remove all line breaks from the string by replacing them with an empty string.

Example 1:

const str = 'this\n is long \n text line \r string \n!';

const withoutLineBreaks = str.replace(/[\r\n]/gm, '');
console.log(withoutLineBreaks); // this is long text line string !

Example 2:

const str = `
This \n is 
long text \n
line string !
`;

const withoutLineBreaks = str.replace(/(\r\n|\n|\r)/gm, "");
console.log(withoutLineBreaks); // this is long text line string !

Example 3:

const str = `
This \n is 
long \r text 
line \n string !
`;

const withoutLineBreaks = str.replace(/(<([^>]+)>)/gi, "");
console.log(withoutLineBreaks); // this is long text line string !