Ravi
Ravi

Reputation: 31

Regex for first character can not be space in JavaScript

Regex for first character cannot be space in JavaScript

I use this but its not working

/^[a-zA-Z0-9]+(\s{0,1}[a-zA-Z0-9])*$/

Upvotes: 2

Views: 18390

Answers (4)

Ritesh Yadav
Ritesh Yadav

Reputation: 321

I have tried "^^ *$" and it worked for me.

Upvotes: 0

The above answers work just fine for single line string but if you want to accept \r (Carriage Return),\n (Line Feed) or \r\n (End Of Line) then you can use the below regex:

[^ ](.*|\n|\r|\r\n)*

[^ ] : First character should not be a space.

(.*|\n|\r|\r\n)*$ : Any character including Carriage Return, Line Feed and End Of Line, any number of times.

Demo

Upvotes: 0

Vishal
Vishal

Reputation: 166

\s matches any character that is unicode whitespace.
\S matches any character that is not unicode white space.

So, a regex that matches to a string whose first character is a non-space character can be any of the following:

/^[^\s].*/  
/^\S.*/

Upvotes: 3

Sam Greenhalgh
Sam Greenhalgh

Reputation: 6136

The following pattern will match any character at the start of a string that is not whitespace.

^\S

If you are trying to match the whole string if it does not begin with whitespace use this.

^\S.*$

Demo

Upvotes: 2

Related Questions