简体   繁体   English

删除特殊字符,但允许空格

[英]Remove special characters but allow spaces

I have the following which removes special characters from being entered into a input 我有以下删除输入中的特殊字符的方法

$('input').on('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});

Is there any way I can add spaces to this, and limit it to only 8 characters being entered? 有什么办法可以在其中添加空格,并将其限制为只能输入8个字符?

Thanks 谢谢

You can do it like this: 您可以这样做:

^[a-zA-Z0-9\\s]+$

Add a whitespace with \\s \\s添加空格

  • Match the beginning of the string ^ 匹配字符串的开头^
  • Your characters including a whitespace [a-zA-Z0-9\\s] 您的字符包括空格[a-zA-Z0-9\\s]
  • Match the end of the string $ 匹配字符串的结尾$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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