Borislav Hadzhiev
Thu Oct 07 2021·2 min read
Photo by Nadine Rupprecht
To remove all line breaks from a string, call the replace()
method on the
string, passing it a regular expression that replaces all occurrences of the
\r
and \n
characters with an empty string. The replace
method returns a
new string with the matched characters replaced.
const str = 'a\n multi \n line \r string \n!'; const withoutLineBreaks = str.replace(/[\r\n]/gm, ''); console.log(withoutLineBreaks); // 👉️ a multi line string !
We have passed a regular expression to the String.replace method.
Let's first cover the g
and m
flags at the end of the regex.
With the g
(global) flag we specify that we want to match all occurrences
of the regex, not just the first one.
With the m
(multiline) flag we specify that we want to match occurrences
over multiple lines.
The [\r\n]
part is a "character class" and is used to match either one of
the characters between the square brackets.
We want to replace both \r
and \n
because the line breaks vary depending on
the operating system.
For example Windows uses \r\n
as end of line character, whereas \n
is the
default in Unix.
The second parameter we pass to the String.replace
method is the replacement
for the matched characters, in our case an empty string.