How to Remove Spaces From a String using JavaScript?
These are the following ways to remove space from the given string:
1. Using string.split() and array.join() Methods
JavaScript string.split() method is used to split a string into multiple sub-strings and return them in the form of an array. The join() method is used to join an array of strings using a separator.
let s = " Geeks for Geeks ";
let res = s.split(" ").join("");
console.log(res);
Output
GeeksforGeeks
2. Using string.replaceAll() Method
JavaScript string.replaceAll()
method replaces all occurrences of a substring from a string. It will replace all the whitespaces with an empty string.
let s = " Geeks for Geeks ";
let res = s.replaceAll(" ", "");
console.log(res);
Output
GeeksforGeeks
3. Using string.trim() Method
The JavaScript string.trim() method removes leading and trailing whitespace from a string.
let s = " Geeks for Geeks ";
let res = s.trim();
console.log(res);
Output
Geeks for Geeks
Note: The trim() method only removes the leading and trailing whitespaces from the string.
4. Using Lodash _.trim() Method
The _.trim() method method removes leading and trailing whitespace from a string.
const _ = require('lodash');
let s = " Geeks for Geeks ";
let res = _.trim(s);
console.log(res);
Output
Geeks for Geeks
5. Using Regular Expressions with string.replace() Method
JavaScript string.replace() method is used to replace a substring. With Regular expressions pattern we can find all spaces (/\s/g) and globally replace all space occurrences with an empty string.
let s = " Geeks for Geeks ";
let res = s.replace(/\s+/g, "");
console.log(res);
Output
GeeksforGeeks
6. Using string.match() with array.join() Method
JavaScript string.match() method returns an array of strings matching the regex pattern given as argument. and array.join() method is used to covert the array of strings to a single string.
let s = " Geeks for Geeks ";
let res = s.match(/\S+/g).join("");
console.log(res);
Output
GeeksforGeeks