Search

Stripping Whitespaces From String in Javascript

  • Share this:
post-title

In computer programming, whitespace is any character or series of characters that represent horizontal or vertical space in typography. When rendered, a whitespace character does not correspond to a visible mark, but typically does occupy an area on a page


Vanilla JavaScript (Trim Leading and Trailing)
var str = " a b    c d e   f g   ";
var newStr = str.trim();
// "a b    c d e   f g"

That method is ES 5, so just in case you could polyfill it (IE 8 and down):

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');
  };
}

jQuery (Trim Leading and Trailing)

And if you’re a jQuery fan:

var str = " a b    c d e f g ";
var newStr = $.trim(str);
// "a b    c d e f g"

Vanilla JavaScript RegEx (Trim Leading and Trailing)
var str = "   a b    c d e f g ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
// "a b    c d e f g"

Vanilla JavaScript RegEx (Trim all Whitespaces)
var str = " a b    c d e   f g   ";
var newStr = str.replace(/\s+/g, '');
// "abcdefg"

Design | UX | Software Consultant
View all posts (125)