[英]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.