Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 478
Techy Avatar asked May 02 '13 09:05

Techy


People also ask

How do you restrict whitespace in regex?

You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace.

What does \d mean in regex?

In regex, the uppercase metacharacter is always the inverse of the lowercase counterpart. \d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ).

What does \+ mean in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.

What is a non-whitespace character in regex?

Non-whitespace character: \S.


2 Answers

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 
like image 119
Bergi Avatar answered Sep 25 '22 06:09

Bergi


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

var regexp = /^\S+$/ 
like image 33
Rikesh Avatar answered Sep 25 '22 06:09

Rikesh