0

This is what I have done so far,

$('.name').keyup(function () {
    var $th = $(this);
    $th.val($th.val().replace(/[^a-zA-Z' ]+( [A-Za-z' ]+)*$/g, function (str) {
        return '';
    }));
});

The above expression allows me to enter A-Z and ' and space. But I want only one space afer a character or word.

Ex. Hello World is ok
but Hello  World should not be accepted.

JSFIDDLE

5 Answers5

3

A simple approach might be better. Just replace repeated spaces with a single space:

.replace(/\s+/, ' ')
user229044
  • 232,980
  • 40
  • 330
  • 338
user428517
  • 4,132
  • 1
  • 22
  • 39
1

Alternately, you could simply replace repeated spaces:

str.replace(/[ ]{2,}/, ' ');
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
0

In your inner most code part, try replacing "replace(/[^a-zA-Z' ]+( [A-Za-z' ]+)" with "replace(/[^a-zA-Z' ]+( [A-Za-z']+)"

I got this hint from this post: Regular expression to allow single space after character or word so you may want to read that too.

Community
  • 1
  • 1
jaadooviewer
  • 368
  • 1
  • 10
0

Try this:

$('.name').keyup(function() {
    var $th = $(this);
    $th.val($th.val().replace(/(\s{2,})|[^a-zA-Z']/g, ' '));
    $th.val($th.val().replace(/^\s*/, ''));
    });

Fiddle

Gustavo Vargas
  • 2,497
  • 2
  • 24
  • 32
  • i can still add multiple spaces. –  Aug 05 '13 at 18:30
  • Sorry, was my mistake, I've paste wrong code, try again plase – Gustavo Vargas Aug 05 '13 at 18:32
  • when i enter character like ,./\] space is left at the start...try entering ./]\ you will find 1 blank spaces at the start... –  Aug 05 '13 at 18:37
  • you there..can my issue be sorted! –  Aug 05 '13 at 18:46
  • Yes its perfect other things are ok just wanted to know how can I remove the space in the begining.. –  Aug 05 '13 at 19:05
  • thats better...one thing I cant use my back arrow key to go back in string .. can that be sorted too.. –  Aug 05 '13 at 19:18
  • I'm not sure if there is a solution for this issue. Since this code changes the whole input content on every 'keyup event', we lost cursor position. So I think the only way to edit text will be with backspace. – Gustavo Vargas Aug 05 '13 at 19:33
  • I appreciate your efforts and time for the answer...however if you come up with the solution please do let me know. –  Aug 05 '13 at 19:53
0

You just need to take out the space at the end of your brackets.

[^a-zA-Z']+( [A-Za-z']+)

Although I would consider putting the space at the end of the first word so you can actually type in real time.

$('.name').keyup(function() {
        var $th = $(this);
        $th.val( $th.val().replace(/([^a-zA-Z'] )+([A-Za-z']+)*$/g, function(str) {  return ''; } ) );
    });
Lily
  • 316
  • 3
  • 10
  • user should not be able to add ,./\][ these characters as well...also on entering 2 space both the space are getting deleted.. –  Aug 05 '13 at 18:33
  • how can i delete just the extra space entered by the user. Also the input tobe limited to a-z and ' –  Aug 05 '13 at 18:35