我有以下功能
的JavaScript
function lettersNumbersOnly(string){
if (/[A-Za-z0-9]/.test(string)) {
console.log('Clean');
}else{
console.log('Not Matching');
}
}
$(".test-input").change(function(){
lettersNumbersOnly($(this).val());
});
如果我将字母和数字放入.test-input
字段,我会得到"Clean"
。但是如果我放置!2@$%
等字符,我仍然得到"Clean"
这不是我想要的。我只想要字母和数字。有什么建议吗?
答案 0 :(得分:1)
使用start and end anchors完成字符串匹配和+
for one or more repetition的character class。
if (/^[A-Za-z0-9]+$/.test(string))