Skip to content Skip to sidebar Skip to footer

Regex To Remove Whitespaces

I'm trying to write a regular expression to remove white spaces from just the beginning of the word, not after, and only a single space after the word. This is the regex that I've

Solution 1:

I think following should take care of all the space replacements for you:

var str      = "   this is     my  string    ";
var replaced = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// repl = 'this is my string'

Solution 2:

This would fit your case:

var myString = "   this is my string    ";
myString = myString.replace(/^\s+/ig, "").replace(/\s+$/ig,"")+" ";
alert(myString);

Tinker: http://tinker.io/e488a/1


Solution 3:

// this should do what you want
var re = new RegExp(/^([a-zA-Z0-9]+\s?)+$/);

Solution 4:

I think the word boundary perfectly suits for this. Try this regexp:

var myString = "   test    ";
myString = myString.replace(/\s+\b|\b\s/ig, "");
alert('"' + myString + '"');

The regexp removes all spaces before all words and the first space after all words


Post a Comment for "Regex To Remove Whitespaces"