JAVASCRIPT
Normalize Multiple Newlines to Single
Clean up text content by replacing multiple consecutive newline characters with a single newline, improving readability and data consistency.
const textWithExcessNewlines = `Line 1
Line 2
Line 3`;
const normalizeNewlinesPattern = /
{2,}/g;
const cleanedText = textWithExcessNewlines.replace(normalizeNewlinesPattern, '
');
console.log(cleanedText);
/* Expected Output:
Line 1
Line 2
Line 3*/
How it works: This regex pattern finds sequences of two or more newline characters (`
`) and replaces them with a single newline. This is incredibly useful for normalizing text data, removing excessive line breaks, and improving text formatting or ensuring consistent data representation, especially with user-generated content or parsed documents.