Reputation: 31
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
Reputation: 687
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.
Upvotes: 0
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
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.*$
Upvotes: 2