字母数字,短划线和下划线但没有空格正则表达式检查JavaScript [英] Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

查看:274
本文介绍了字母数字,短划线和下划线但没有空格正则表达式检查JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试检查正则表达式的输入。

Trying to check input against a regular expression.

该字段应仅允许使用字母数字字符,破折号和下划线,并且不应允许空格。

The field should only allow alphanumeric characters, dashes and underscores and should NOT allow spaces.

但是,下面的代码允许使用空格。

However, the code below allows spaces.

我缺少什么?

var regexp = /^[a-zA-Z0-9\-\_]$/;
var check = "checkme";
if (check.search(regexp) == -1)
    { alert('invalid'); }
else
    { alert('valid'); }


推荐答案


然而,下面的代码允许使用空格。

However, the code below allows spaces.

不,它没有。但是,它只会在长度为1的输入上匹配。对于长度大于或等于1的输入,在字符类后面需要 +

No, it doesn't. However, it will only match on input with a length of 1. For inputs with a length greater than or equal to 1, you need a + following the character class:

var regexp = /^[a-zA-Z0-9-_]+$/;
var check = "checkme";
if (check.search(regexp) == -1)
    { alert('invalid'); }
else
    { alert('valid'); }

请注意, - (in这个实例)也不需要 _ 转义。

Note that neither the - (in this instance) nor the _ need escaping.

这篇关于字母数字,短划线和下划线但没有空格正则表达式检查JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆