How to Trim Whitespace in JavaScript

  1. Use the trim() Method in JavaScript to Remove Whitespace
  2. Use the replace() Method in JavaScript to Remove Whitespace
How to Trim Whitespace in JavaScript

In JavaScript, we can remove single or multiple spaces from a string with the help of default JavaScript string methods like trim() and replace().

Use the trim() Method in JavaScript to Remove Whitespace

The trim() method removes the extra white spaces off a declared string from both sides in JavaScript. In the example below, we will initialize a string containing spaces and test the trim method for replacing spaces from both ends.

Example Code:

<script>
let string = "    Delft stack is a best website   "
let result = string.trim()
console.log("original string: "+string)
console.log("updated string: "+result)
</script>

Output:

"original string:     Delft stack is a best website   "
"updated string: Delft stack is a best website"

We used the trim() method on the string to remove those extra spaces and generate a new result string. Displayed the updated strings to see the result and differentiate the working methods.

Use the replace() Method in JavaScript to Remove Whitespace

The replace() is a pre-defined method used to replace the defined portion of that string with another. It searches the defined string portion from the complete declared string and replaces it with the given value.

We will initialize a string containing spaces and test the replace method for removing all the spaces. We will use a regular expression with the modifier set (g) to replace all instances.

Regular Expression:

let regex = /\s+/g

Example Code:

<script>
let string = "Delft stack is a good website to learn programming"
let regex = /\s+/g
let result = string.replace(regex, '');

console.log("original string: "+string)
console.log("updated string: "+result)
</script>

Output:

"original string: Delft stack is a good website to learn programming"
"updated string: Delftstackisagoodwebsitetolearnprogramming"

In the above code we initialized regex variable with required regular expression /\s+/g. Then used replace()method on the initialized string with 2 arguments replace(regex,'').

In the first argument, we provided regex (regular expression) to replace all the spaces. It will find out the all space (" ") in the string and replace it with no space ("").

Related Article - JavaScript String