正则表达式,在第一个/最后一个名称验证中只允许一个空格

时间:2014-02-20 04:22:47

标签: javascript regex string

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

使用RegExp:

var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);

测试Exapmle:

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;
                }

3 个答案:

答案 0 :(得分:2)

使用捕获组:

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'

答案 1 :(得分:0)

我可能会懒得保持简单并使用两个单独的RE:

// 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(/^ ?/, '');

答案 2 :(得分:0)

这个怎么样:

replace(/^ | $|( ) +/, $1)?