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:

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** 

Answers:

Answer

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)

See demo here.

Answer

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.

Answer

Try this regex

/^(\w+)(\s+)/

and your code:

result = inputString.replace(/^(\w+)(\s+)?/g, "$1");
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.