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:
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'
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);
|
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
const _ = require( 'lodash' );
let str = "----GeeksforGeeks----" ;
console.log(_.trim(str, "-" ))
|
Output:
GeeksforGeeks
Last Updated :
22 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...