Javascript 在名/姓验证中只允许一个空格的正则表达式
我正在尝试编写一个正则表达式来删除单词开头的空格,而不是后面的空格,并且只删除单词后面的单个空格 使用的RegExp:Javascript 在名/姓验证中只允许一个空格的正则表达式,javascript,regex,string,Javascript,Regex,String,我正在尝试编写一个正则表达式来删除单词开头的空格,而不是后面的空格,并且只删除单词后面的单个空格 使用的RegExp: var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/); 测试示例: 1) test[space]ing - Should be allowed 2) testing - Should be allowed 3) [space]testing - Should be allowed but have to trim the space at
var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);
测试示例:
1) test[space]ing - Should be allowed
2) testing - Should be allowed
3) [space]testing - Should be allowed but have to trim the space at the first
4) testing[space] - Should be allowed but have to trim the space at the last
5) testing[space][space] - should be allowed but have to trim the space at the last
6) test[space][space]ing - one space should be allowed but the remaining spaces have to be trimmed.
你知道如何使用正则表达式实现这一点吗
编辑:
我有这个
var regExp = /^(\w+\s?)*\s*$/;
if(regExp.test($('#FirstName').val())){
$('#FirstName').val().replace(/\s+$/, '');
}else{
var elm = $('#FirstName'),
msg = 'First Name must consist of letters with no spaces';
return false;
}
我可能懒得保持它的简单并使用两个单独的REs:
// Collapse any multiple spaces into one - handles cases 5 & 6
str.replace(/ {2,}/, ' ');
// Trim any leading space
str.replace(/^ /, '');
或者,作为一种说法:
var result = str.replace(/ {2,}/, ' ').replace(/^ ?/, '');
这个怎么样:
replace(/^ | $|( ) +/, $1)?
使用捕获组:
var re = /^\s+|\s+$|(\s)\s+/g;
'test ing'.replace(re, '$1') // => 'test ing'
'testing'.replace(re, '$1') // => 'testing'
' testing'.replace(re, '$1') // => 'testing'
'testing '.replace(re, '$1') // => 'testing'
'testing '.replace(re, '$1') // => 'testing'
'test ing'.replace(re, '$1') // => 'test ing'
最后(6)个字符串的预期结果是什么
test[space]ing
或false
?@falsetest[space]ing
应为示例不包含不允许的大小写。您能给出一个完全不允许的示例吗?@falsetru not allowed case为空valfirstname@coderman,如果不允许,var name=$(“#FirstName').val().replace(re,“$1”);如果(name){…}else{…return false;}
就足够了。只允许两个可能的输入,比如testing
和test ing
,其余的空格必须被修剪。@coderman,在回答中,空格会随着你的注释而修剪,不是吗?te sting
必须接受,因为它之间只有一个空格。@coderman,te sting.replace(re,$1')
返回“te sting”
。