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.
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
\n, because the line breaks vary depending on the operating system. For e.g, Windows uses
\r\nas the end of line character, whereas
\nis 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.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!