How to remove all line breaks from a string?
Use a regular expression that matches all forms of line breaks and replace them with an empty string. In many languages, you can do something like:
const input = "Line 1\nLine 2\r\nLine 3\n"; const output = input.replace(/(\r\n|\r|\n)/g, ""); console.log(output); // "Line 1Line 2Line 3"
This effectively removes all line breaks (whether they are \n
, \r\n
, or just \r
).
1. Why (\r\n|\r|\n)
?
\r\n
is the Windows-style line break.\r
alone is a classic Mac-style line break.\n
alone is a Unix-style line break.
By grouping them with the alternation operator |
, you can match any type of newline sequence.
2. Variation: /\r?\n/g
Another common pattern is:
input.replace(/\r?\n/g, "");
\r?\n
means “an optional carriage return (\r?
) followed by a newline (\n
).”- This handles
\n
(Unix) and\r\n
(Windows), but may not catch the rare standalone\r
(older Mac style).
If you want to be absolutely sure all line breaks are removed, stick with (\r\n|\r|\n)
.
3. Cross-Language Examples
3.1 Python
text = "Line 1\nLine 2\r\nLine 3" text_no_breaks = re.sub(r'(\r\n|\r|\n)', '', text)
(You’ll need import re
for regex.)
3.2 Java
String text = "Line 1\nLine 2\r\nLine 3"; String textNoBreaks = text.replaceAll("(\\r\\n|\\r|\\n)", "");
3.3 C#
string text = "Line 1\nLine 2\r\nLine 3"; string textNoBreaks = Regex.Replace(text, "(\r\n|\r|\n)", "");
(You’ll need using System.Text.RegularExpressions;
)
4. Final Thoughts
- Regex is a flexible way to handle various newline sequences.
- If you only deal with one newline style (e.g.,
\n
), you can use a simpler pattern. - Consider whether you want to remove all line breaks entirely or replace them with a single space. For instance,
"$1 "
, if you want to preserve spacing.
Bonus: Strengthen Your Regex & Coding Skills
If you want to take your JavaScript, coding interview, or system design expertise further, check out these DesignGurus.io resources:
-
Grokking JavaScript Fundamentals
Learn closures, prototypes, async patterns, and more—essential for tackling advanced string manipulation and debugging. -
Grokking the Coding Interview: Patterns for Coding Questions
Practice coding patterns that frequently appear in interviews and real-life development tasks. -
Grokking Python Fundamentals Dive into Python essentials.
For personalized feedback, explore Mock Interviews:
You can also find free tutorials on the DesignGurus.io YouTube channel.
Summary: Remove line breaks by replacing all newline types (\r\n
, \r
, and \n
) with ""
, typically via a regex like:
inputString.replace(/(\r\n|\r|\n)/g, "");