Replace multiple whitespaces with single whitespace in JavaScript string
Something like this:
var s = " a b c ";console.log( s.replace(/\s+/g, ' '))
You can augment String to implement these behaviors as methods, as in:
String.prototype.killWhiteSpace = function() { return this.replace(/\s/g, '');};String.prototype.reduceWhiteSpace = function() { return this.replace(/\s+/g, ' ');};
This now enables you to use the following elegant forms to produce the strings you want:
"Get rid of my whitespaces.".killWhiteSpace();"Get rid of my extra whitespaces".reduceWhiteSpace();
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")