Introduction
In this lab, we will explore how to compact whitespaces in a string using JavaScript. We will utilize the String.prototype.replace() method and a regular expression to replace all occurrences of two or more whitespace characters with a single space. This will help us to effectively format and clean up text data in our web applications.
Function to Compact Whitespaces in a String
To compact whitespaces in a string, use the compactWhitespace() function.
- It uses
String.prototype.replace()with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space. - The function takes a string as an argument and returns the compacted string.
const compactWhitespace = (str) => str.replace(/\s{2,}/g, " ");
Example usage:
compactWhitespace("Lorem Ipsum"); // 'Lorem Ipsum'
compactWhitespace("Lorem \n Ipsum"); // 'Lorem Ipsum'
Summary
Congratulations! You have completed the Compact Whitespaces lab. You can practice more labs in LabEx to improve your skills.