;

How to Remove Extra Whitespace from the String in Javascript


Tutorialsrack 27/02/2022

In this article, you’ll learn how to remove extra whitespace from the string in javascript. You can use the 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 \s+.

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 trim() function:

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:

  • \s: matches any whitespace symbol: spaces, tabs, and line breaks
  • +: match one or more of the preceding tokens (referencing \s)
  • g: the g at the end indicates iterative searching throughout the full string

I hope this article will help you to understand how to remove extra whitespace from the string in javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags