Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The method to eliminate unnecessary white spaces in a string, while retaining symbols like '\n', is to use regular expressions. The following regular expression pattern can be used to match any sequence of consecutive whitespace characters (spaces, tabs, etc.) except for newline characters:

/ +(?=[^\n])/g

Then, the replace() method can be used to replace all matches of this pattern with a single space character:

const str = "Hello,\n   world!";
const trimmedStr = str.replace(/ +(?=[^\n])/g, " ");

console.log(trimmedStr); // "Hello,\n world!"

In this example, the original string contained three consecutive spaces before the word "world". These spaces were replaced with a single space, leaving the newline character intact.