How to remove empty lines in a multiline string?

How to remove empty lines in a multiline string?
Photo by nathan gordon / Unsplash

To trim empty lines in a JavaScript multiline string, you can use the `replace()` method with a regular expression. Here's an example code snippet:

const multiLineString = `Hello
World

How are you?

`;
const trimmedString = multiLineString.replace(/^\s*[\r\n]/gm, '');
console.log(trimmedString);

The regular expression ^\s*[\r\n] matches any whitespace characters (\s*) at the beginning of a line (^) followed by a line break ([\r\n]). The g and m flags are used to apply the regular expression globally and to treat the input string as a multiline string, respectively.

The replace() method replaces all occurrences of the regular expression with an empty string, effectively removing any empty lines from the string. The resulting string is stored in the trimmedString variable, which we then output to the console using console.log().