remove only break lines of start and end of string in javascript

You can use a regular expression to remove the line breaks at the start and end of a string in Javascript. Here's a code snippet that demonstrates how to do this:

index.tsx
let str = "\n\nThis is a string\nwith line breaks\n\n";

// Remove line breaks at start and end of string
str = str.replace(/^\s+|\s+$/g, "");

console.log(str); // "This is a string\nwith line breaks"
202 chars
7 lines

The regular expression ^\s+|\s+$ matches one or more whitespace characters (\s+) at the start of the string (^) OR (|) one or more whitespace characters at the end of the string ($). The g flag makes the regular expression global, meaning that it will match all occurrences of the pattern in the string.

The replace() method replaces all matches of the regular expression with an empty string, effectively removing the line breaks at the start and end of the string.

gistlibby LogSnag