[英]Regular expression to allow just single blank space after a character or word
這是我迄今為止所做的,
$('.name').keyup(function () {
var $th = $(this);
$th.val($th.val().replace(/[^a-zA-Z' ]+( [A-Za-z' ]+)*$/g, function (str) {
return '';
}));
});
上面的表達式允許我輸入 AZ 和 ' 和空格。 但我只想要一個字符或單詞后的空格。
Ex. Hello World is ok
but Hello World should not be accepted.
一個簡單的方法可能會更好。 只需用一個空格替換重復的空格:
.replace(/\s+/, ' ')
或者,您可以簡單地替換重復的空格:
str.replace(/[ ]{2,}/, ' ');
在你最里面的代碼部分,嘗試用“replace(/[^a-zA-Z' ]+”替換“replace(/[^a-zA-Z' ]+( [A-Za-z' ]+)” ( [A-Za-z']+)"
我從這篇文章中得到了這個提示: Regular expression to allow single space after character or word so you may want to read that.
試試這個:
$('.name').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/(\s{2,})|[^a-zA-Z']/g, ' '));
$th.val($th.val().replace(/^\s*/, ''));
});
你只需要去掉括號末端的空間。
[^a-zA-Z']+( [A-Za-z']+)
盡管我會考慮將空格放在第一個單詞的末尾,以便您可以實時輸入。
$('.name').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/([^a-zA-Z'] )+([A-Za-z']+)*$/g, function(str) { return ''; } ) );
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.