remove newlines from the sides of a string in javascript

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.tsx
let str = "\n\nHello, world!\n\n";
console.log(str.trim()); // Outputs "Hello, world!"
87 chars
3 lines

And here's an example of using a regex to remove newlines from the sides of a string:

index.tsx
let str = "\n\nHello, world!\n\n";
let trimmed = str.replace(/^\n+|\n+$/g, "");
console.log(trimmed); // Outputs "Hello, world!"
129 chars
4 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