eSnippets.net, a code gallery for creating, saving and sharing all kinds of code snippets.

Strip Whitespace From String — Javascript

Posted On: Saturday, May 10, 2014 at 9:52 AM

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"

You need to be logged in to comment! x

rpjs

Joined on Saturday, May 3, 2014
Contributed 29 Snippets

Get Social and Share

Tags