0

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

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

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

4 回答 4

2

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

var str      = "   this is     my  string    ";
var replaced = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// repl = 'this is my string'
于 2013-05-24T14:37:38.540 回答
1

这将适合您的情况:

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

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

于 2013-05-24T14:15:06.757 回答
0

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

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

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

于 2014-04-30T08:09:38.647 回答
0
// this should do what you want
var re = new RegExp(/^([a-zA-Z0-9]+\s?)+$/);
于 2013-05-24T14:17:00.873 回答