简体   繁体   中英

Regular expression for not allowing spaces in the input field

I have a username field in my form. I want to not allow spaces anywhere in the string. I have used this regex:

var regexp = /^\S/;

This works for me if there are spaces between the characters. That is if username is ABC DEF . It doesn't work if a space is in the beginning, eg <space><space>ABC . What should the regex be?

While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string :

var regexp = /^\S*$/; // a string consisting only of non-whitespaces

使用+加号(匹配一个或多个前面的项目),

var regexp = /^\S+$/

这将有助于找到开头、中间和结尾的空格:

var regexp = /\\s/g

If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()

Than Below string will work

'^\\S*$'

It's same regex @Bergi mentioned just the string version for new RegExp constructor

This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.

/^([A-z0-9!@#$%^&*().,<>{}[\\]<>?_=+\\-|;:\\'\\"\\/])*[^\\s]\\1*$/

Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.

If you want just alphanumeric characters then change what is in the [] like so:

/^([Az])*[^\\s]\\1*$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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