Soarabh
Soarabh

Reputation: 2950

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 tried:

var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);
Output - 
re.test("")
true - required false
re.test(" ")
false
re.test(" word")
false - required word - true 
re.test(" word ")
false - required word - true 
re.test("word ")
true
re.test("word  ")
false - - required word(with single space ) - true 

Exp:

See, I have to send a request to backend where if

1) key term is ""(blank) no need to send the request. 
2) If key is " string" need to send the request. 
3) If user enter something like this "string    string" need to send the request. 
4) if user enter "string " need to send the request. 
5) if user enter string with a space need to send the request but at the moment he enter another space no need to send the request. 

This thing i am trying to achieve using regular expression.

Upvotes: 0

Views: 1536

Answers (4)

Lukas Kral
Lukas Kral

Reputation: 997

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

Upvotes: 0

anubhava
anubhava

Reputation: 784898

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'

Upvotes: 2

bert
bert

Reputation: 466

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

Upvotes: 0

Sébastien Renauld
Sébastien Renauld

Reputation: 19662

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

Upvotes: 1

Related Questions