[英]HTML pattern validation for MUI textfiled that accept only *first name one space and first character of the last name*
[英]Regex that allows only one space in the first/last name validation
我正在嘗試編寫一個正則表達式以從單詞的開頭而不是單詞后面刪除空格,並且僅在單詞后面刪除一個空格。
使用過的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 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'
我可能會懶於保持簡單並使用兩個單獨的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(/^ ?/, '');
這個怎么樣:
replace(/^ | $|( ) +/, $1)?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.