[英]RegExp which allow only one space in between words
I'm trying to write a regular expression to remove white spaces from just the beginning of the word, not after, and only a single space after the word. 我正在尝试编写一个正则表达式以从单词的开头而不是单词后面删除空格,并且仅在单词后面删除一个空格。
Used RegExp: 使用过的RegExp:
var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);
Test Exapmle: 测试实例:
1) wordX[space] - Should be allowed
2) [space] - Should not be allowed
3) WrodX[space][space]wordX - Should be allowed
4) WrodX[space][space][space]wordX - Should be allowed
5) WrodX[space][space][space][space] - Should be not be allowed
6) WrodX[space][space] - Allowed with only one space the moment another space is entered **should not be allowed**
Try this one out: 试试这个:
^\s*\w+(\s?$|\s{2,}\w+)+
Test cases ("s added for clarity): 测试用例(为清楚起见添加了“”):
"word" - allowed (match==true)
"word " - allowed (match==true)
"word word" - allowed (match==true)
"word word" - allowed (match==true)
" " - not allowed (match==false)
"word " - not allowed (match==false)
"word " - not allowed (match==false)
" word" - allowed (match==true)
" word" - allowed (match==true)
" word " - allowed (match==true)
" word word" - allowed (match==true)
Try this: 尝试这个:
var re = /\S\s?$/;
This matches a non-space followed by at most one space at the end of the string. 这与一个非空格匹配,在字符串末尾最多匹配一个空格。
BTW, there's no need to use new RegExp
when you're providing a regexp literal. 顺便说一句,当您提供正则表达式文字时,无需使用new RegExp
表达式。 That's only needed when converting a string to a RegExp. 仅在将字符串转换为RegExp时才需要。
Try this regex 试试这个正则表达式
/^(\w+)(\s+)/
and your code: 和您的代码:
result = inputString.replace(/^(\w+)(\s+)?/g, "$1");
try to use code that i am giving you and implement with javascript, i hope it will for you fine HTML Code 尝试使用我给您的代码并使用javascript实现,希望它对您有帮助。
<input type="test" class="name" />
Javascript Code: JavaScript代码:
$('.name').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/(\s{2,})|[^a-zA-Z']/g, ' '));
$th.val($th.val().replace(/^\s*/, ''));
});
This code does not allow more than one spaces between characters or words. 此代码在字符或单词之间不允许有多个空格。 Check here JsFiddle Link . 在这里检查JsFiddle链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.