Explain Codes LogoExplain Codes Logo

How to remove all line breaks from a string

javascript
regex
string-manipulation
text-processing
Anton ShumikhinbyAnton Shumikhin·Jan 10, 2025
TLDR

Effortlessly strip line breaks in JavaScript: employ .replace(/\s+/g, ' ') for replacing line breaks with spaces, or .replace(/\r?\n|\r/g, '') to wipe out all line breaks mercilessly:

let cleanString = yourString.replace(/\r?\n|\r/g, '');

Just switch yourString with your actual string data — and voila! — you're one step closer to that sweet single-line string life.

Demystifying regex

Different operating systems use different line break characters — namely \r\n (Windows), \n (Unix/Linux), and \r (ye good ol' Mac). Our regex pattern /\r?\n|\r/g is a true diplomat — it handles line breaks on all these platforms.

Adding a finishing touch, you might use the .trim() method to lop off any unwanted leading or trailing whitespace:

let cleanString = yourString.replace(/\r?\n|\r/g, '').trim();

Now your string's as clean as a hound's tooth.

The joys of textareas

Working with <textarea> in web apps? Fetch the content with .value, and then give it the good ol' regex treatment:

const textareaContent = document.querySelector('textarea').value; const tidyText = textareaContent.replace(/\r?\n|\r/g, '');

Who knew efficient text manipulation could bring so much delightful order to user inputs?

Mixing and matching patterns

While our primary regex gets down to business, consider these alternatives for diverse scenarios:

  • To focus solely on the habit of mixing newlines with carriage returns, try /(\r\n|\r)/g.
  • For a grander cleanup, use .replace(/\s+/g, ' ') to replace line breaks and other consecutive spaces with a single space.

Go on, give method chaining a whirl:

let processedText = yourString .replace(/\r?\n|\r/g, ' ') // Wave goodbye to those pesky line breaks .trim(); // And say adios to any trailing or leading spaces

Beyond the basics — special cases and fine-tuning

CSVs and HTML

Working with CSVs? Keep your line breaks between records but simultaneously expel them from individual fields. With HTML, remember that in the wild world of browsers, whitespace collapses, so replace multiple spaces with &nbsp;.

Preprocessing quirks

Newlines don't care about character encoding, but if you have to take it into account, ensure you preprocess. By the way, did you know JavaScript treats strings in UTF-16? I guess you do now.

Readability matters

Sure, the code works. But is it readable? If it gets complicated, consider wrapping it up in a function. Trust us, stripLineBreaks(yourString) looks neater and makes your code easier to understand, not to mention impress your dev buddies.