Sometimes, we want to remove whitespaces inside a string in JavaScript.
In this article, we’ll look at how to remove whitespaces inside a string in JavaScript.
How to remove whitespaces inside a string in JavaScript?
To remove whitespaces inside a string in JavaScript, we can call the string replace
method.
For instance, we write
const s = "hello world".replace(/s/g, "");
to call replace
with /s/g
and ''
to replace all whitespaces with empty strings.
We use s
to match whitespaces.
g
makes replace
do the replacement on all matches.
Conclusion
To remove whitespaces inside a string in JavaScript, we can call the string replace
method.