Grow your CSS skills. Land your dream job.

Last updated on:

Strip Whitespace From String

Whitespace, meaning tabs and spaces.

// Remove leading and trailing whitespace
// Requires jQuery
var str = " a b    c d e f g ";
var newStr = $.trim(str);
// "a b c d e f g"

// Remove leading and trailing whitespace
// JavaScript RegEx
var str = "   a b    c d e f g ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
// "a b c d e f g"

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

Doesn't work with other types of whitespace though, for instance   (thin space) or   (non-breaking space)

Comments

  1. You don’t need that “+” in the last case: “g” modifier takes care of that.

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".