string.replace() method with a regular expression to remove extra whitespace from the string. The dedicated RegEx to match any whitespace character is
\s. Expand the whitespace selection from a single space to multiple spaces using the regex and the regex is
So combine the
string.replace() method and the RegEx and replace it with a single string.
The starting and ending spaces will be kept and stripped down to a single space. So for removing the whitespace from the starting and end of the string, we used the
const sentence = ' Here is the string with a lot of Whitespace. '.replace(/\s+/g, ' ').trim() console.log(sentence); //Output ==> 'Here is the string with a lot of Whitespace.'
Let’s understand what the regular expression does:
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!