Reputation: 2950
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:
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**
Upvotes: 0
Views: 10868
Reputation: 220
try to use code that i am giving you and implement with javascript, i hope it will for you fine HTML Code
<input type="test" class="name" />
Javascript Code:
$('.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.
Upvotes: 1
Reputation: 135752
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)
Upvotes: 3
Reputation: 10347
Try this regex
/^(\w+)(\s+)/
and your code:
result = inputString.replace(/^(\w+)(\s+)?/g, "$1");
Upvotes: 0
Reputation: 780787
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. That's only needed when converting a string to a RegExp.
Upvotes: 0