Open In App

String strip() in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

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:

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. 

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

Javascript




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


Output

Before string:'    GeeksforGeeks     '
After string :'GeeksforGeeks'

Approach 2: Using the Javascript string replace() method

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

Example: This example uses the javascript replace() method to remove the extra spaces from the string.

Javascript




function strip(string) {
    return string.replace(/^\s+|\s+$/g, '');
}
 
const string = "    GeeksforGeeks     ";
console.log("Before string:'" + string + "'");
 
console.log("After string :'" + strip(string) + "'");


Output

Before string:'    GeeksforGeeks     '
After string :'GeeksforGeeks'

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

In this method, split() is used to split the string at each whitespace. Then, the filter() method is called on the resulting array to remove any empty strings or strings consisting only of whitespace, and join() is used to concatenate the string without whitespace.

Example: This example shows the implementation of the above-explained approach.

Javascript




function removeWhitespace(str) {
  return str.split(' ').filter(Boolean).join('');
}
const str = "  Hello,    Geeks!   ";
let stringAfterRemoval = removeWhitespace(str);
console.log(stringAfterRemoval);


Output

Hello,Geeks!

Approach 4: Using Lodash _.trim() Method

Lodash _.trim() Method removes leading and trailing white spaces or specified characters from the given string.

Syntax:

_.trim(string, chars);

Example: In this example, we are trimming the given string by “-” by the use of the _.trim() method.

Javascript




// Defining Lodash variable
const _ = require('lodash');
 
let str = "----GeeksforGeeks----";
 
// Using _.trim() method
console.log(_.trim(str, "-"))


Output:

GeeksforGeeks


Last Updated : 22 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads