jQuery只允许数字,字母和连字符 [英] jQuery only allow numbers,letters and hyphens
问题描述
如何使用jQuery从字符串中删除数字,字母和连字符以外的所有内容?
How can I remove everything but numbers,letters and hyphens from a string with jQuery?
我发现此代码仅允许使用字母数字字符,但不确定如何添加连字符.
I found this code which allows only alphanumerical characters only but I'm not sure how I would go about adding a hyphen.
$('#text').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
推荐答案
您只需要将正则表达式更改为"^[a-zA-Z0-9\-]+$"
.
You just have to change the regexp to this : "^[a-zA-Z0-9\-]+$"
.
请注意,连字符使用\
进行了转义,否则,它用于指定类似a-z
的范围(字符从a
到z
).
Note that the hyphen is escaped using \
, otherwise it is used to specify a range like a-z
(characters from a
to z
).
此代码将仅检查最后一个键入的字符是否在允许的列表中,您可能还想检查在字段中粘贴后是否仍然正确:
This code will only check if the last typed character is in the allowed list, you might also want to check if after a paste in your field, the value is still correct :
// The function you currently have
$('#text').keypress(function (e) {
var allowedChars = new RegExp("^[a-zA-Z0-9\-]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (allowedChars.test(str)) {
return true;
}
e.preventDefault();
return false;
}).keyup(function() {
// the addition, which whill check the value after a keyup (triggered by Ctrl+V)
// We take the same regex as for allowedChars, but we add ^ after the first bracket : it means "all character BUT these"
var forbiddenChars = new RegExp("[^a-zA-Z0-9\-]", 'g');
if (forbiddenChars.test($(this).val())) {
$(this).val($(this).val().replace(forbiddenChars, ''));
}
});
这篇关于jQuery只允许数字,字母和连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!