[javascript] 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, e.g. <space><space>ABC. What should the regex be?

This question is related to javascript regex

The answer is


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

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:

/^([A-z])*[^\s]\1*$/


This will help to find the spaces in the beginning, middle and ending:

var regexp = /\s/g


Use + plus sign (Match one or more of the previous items),

var regexp = /^\S+$/

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