You can use the trim()
method in JavaScript to remove whitespace from both sides of a string, including newlines. However, if you only want to remove newlines specifically, you can use a regular expression (regex) to target them.
Here's an example of using trim()
to remove newlines from the sides of a string:
index.tsx87 chars3 lines
And here's an example of using a regex to remove newlines from the sides of a string:
index.tsx129 chars4 lines
In this example, the regex /^\n+|\n+$/g
matches one or more newline characters (\n
) at the beginning of the string (^
) or one or more newline characters at the end of the string ($
), and replaces them with an empty string.
gistlibby LogSnag