How to remove extra spaces in a JavaScript String

Mohammed Hammoud
Jul 20, 2017 · 1 min read

Recently I wanted to remove extra spaces inside of string. The easiest way to do that was by extending JavaScript’s String object. You could obviously if you prefer just wrap the return statement inside of a function and use it on demand instead.

String.prototype.removeExtraSpaces = function() {
return this.replace(/\s+/g,' ').trim();
}
> Run: "This is my string ".removeExtraSpaces();
> Output: "This is my string"

Happy hacking…

)

Mohammed Hammoud
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade