How to usestring.trim() method in Javascript

Here, we will be using the trim() method. We can strip a string using the trim() method and remove unnecessary trailing and leading spaces and tabs from the string. 

Example: In this example, we will remove the extra spaces from the string using the trim method of JavaScript.

Javascript




const string = "    w3wiki     ";
console.log("Before string:'" + string + "'");
console.log("After string :'" + string.trim() + "'");


Output

Before string:'    w3wiki     '
After string :'w3wiki'

String strip() in JavaScript

In this article, the task is to remove all leading and trailing spaces and tabs from the string. We will use a method to reach the goal. 

These are the following methods:

Table of Content

  • Using string.trim() method
  • Using the Javascript string replace() method
  • Using split(), filter() and join() Method
  • Using Lodash _.trim() Method

Similar Reads

Approach 1: Using string.trim() method

Here, we will be using the trim() method. We can strip a string using the trim() method and remove unnecessary trailing and leading spaces and tabs from the string....

Approach 2: Using the Javascript string replace() method

...

Approach 3: Using split(), filter() and join() Method

Here we will be making a user-defined function. We will be writing JavaScript to strip the string and remove unnecessary spaces....

Approach 4: Using Lodash _.trim() Method

...