There’re many occasions where we may want to remove spaces from a string with JavaScript.
In this article, we’ll look at how to remove spaces from a string with JavaScript.
Search for Spaces with Regex and Replace Them
We can search for spaces with regex and replace them with the JavaScript string’s replace
method.
For instance, we can write:
const result = ' abc '.replace(/ +/g, '');
console.log(result)
to remove one or more spaces with the replace
method.
We just have a space with a plus sign after it to search for one or spaces.
Then g
flag lets us search for all instances of spaces in a string.
Therefore, result
should be 'abc'
.
Alternatively, we can search for instances of one or more spaces and replace them with:
const result = ' abc '.replace(/\s+/g, '');
console.log(result)
Also, we can search for instances of single spaces and replace them with:
const result = ' abc '.replace(/ /g, '');
console.log(result)
And we get the same result.
Also, we can use the \s
pattern to search for a single space and replace them.
For instance, we can write:
const result = ' abc '.replace(/\s/g, '');
console.log(result)
to get the same result.
The fastest way to replace all empty spaces is:
const result = ' abc '.replace(/ /g, '');
console.log(result)
for short strings.
And for long strings:
const result = ' abc '.replace(/ +/g, '');
console.log(result)
is fastest.
String.prototype.split
We can also split strings with the split
method using a space as a separator.
And then we join the split string array back together with join
.
For instance, we can write:
const result = ' abc '.split(' ').join('');
console.log(result)
And we get the same result as the previous examples.
Conclusion
We can use the replace
method with a regex to search for all spaces and replace them with empty strings to remove all whitespace from a string.
Also, we can use the split
method to split a string by a whitespace character string and join it back together with join
to do the same thing.