;

How to Remove All Line Breaks From a String Using Javascript


Tutorialsrack 30/03/2022 Jquery Javascript

In this article, you’ll learn how to remove all line breaks from a string using Javascript. We used the replace() method to remove all the line breaks from a string and pass a regular expression that replaces all the occurrences of the \n and \r with an empty character.

Here is an example to remove all line breaks from a string using javascript.

const str = '\nbreak all\r line breaks\n from a multi \r\n line \r string \n!';

const stringWithoutLineBreaks = str.replace(/[\r\n]/gm, '');
console.log(stringWithoutLineBreaks); 
// Output 👉️ break all line breaks from a multi  line  string !

Let’s understand what the regular expression does:

  • \r\n: We want to replace both \r and \n, because the line breaks vary depending on the operating system. For e.g, Windows uses \r\n as the end of line character, whereas \n is the default in Unix.
  • g: the g (global) flag at the end indicates iterative searching throughout the full string.
  • m: m (multiline) flag at the end matches occurrences over multiple lines.

I hope this article will help you to understand how to remove all line breaks from a string using Javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags