正则表达式删除空格

时间:2013-05-24 14:09:12

标签: javascript regex

我正在尝试编写一个正则表达式来从单词的开头处删除空格,而不是在单词后面的单个空格中删除空格。

这是我尝试过的正则表达式:

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 

经验:

请参阅,我必须向后端发送请求,如果

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. 

这是我试图用正则表达式实现的。

4 个答案:

答案 0 :(得分:2)

我认为以下应该为您处理所有空间替换:

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

答案 1 :(得分:1)

这适合你的情况:

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

修补匠:http://tinker.io/e488a/1

答案 2 :(得分:0)

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

答案 3 :(得分:0)

我认为边界这个词非常适合这个。试试这个正则表达式:

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

正则表达式删除所有单词之前的所有空格以及所有单词之后的第一个空格