How to remove extra spaces in a JavaScript String
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…
