Remove Line Breaks with Javascript
Updated: March 23, 2020This hot tip is all about using plain JavaScript code to remove line breaks from a string.
In order to remove line breaks, we have to take into consideration three different types of line breaks, depending on the three operating system: (\r\n)
for Windows, (\n)
for Linux and (\r)
for macOS.
Let's first define the string variable with some Hipster Ipsum text that we need to format:
Now, using .replace()
method with a regular expression we can remove all the above types of line breaks:
If we want to replace all 3 types of line breaks with a space:
Finally, in case you want to replace line breaks with a non breaking space: