简体   繁体   中英

Regular expression to allow just single blank space after a character or word

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

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

.replace(/\s+/, ' ')

或者,您可以简单地替换重复的空格:

str.replace(/[ ]{2,}/, ' ');

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.

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

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 ''; } ) );
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM