gpt4 book ai didi

javascript - 在名字/姓氏验证中只允许一个空格的正则表达式

转载 作者:行者123 更新时间:2023-11-30 17:36:42 24 4
gpt4 key购买 nike

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

使用正则表达式:

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

最佳答案

使用捕获组:

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'

关于javascript - 在名字/姓氏验证中只允许一个空格的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21898082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com