Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex - no white space at beginning + allow space in the middle

I would like to have a regex which matches the string with NO whitespace(s) at the beginning. But the string containing whitespace(s) in the middle CAN match. So far i have tried below

[^-\s][a-zA-Z0-9-_\\s]+$

Regular expression visualization

Debuggex Demo

Above is not allowing whitespace(s) at the beginning, but also not allowing in the middle/end of the string. Please help me.

like image 717
sanbhat Avatar asked Nov 14 '13 09:11

sanbhat


People also ask

How do I get rid of white space in regex?

The replaceAll() method accepts a string and a regular expression replaces the matched characters with the given string. To remove all the white spaces from an input string, invoke the replaceAll() method on it bypassing the above mentioned regular expression and an empty string as inputs.

Which modifier ignores white space in regex?

Turn on free-spacing mode to ignore whitespace between regex tokens and allow # comments. Turn on free-spacing mode to ignore whitespace between regex tokens and allow # comments, both inside and outside character classes.

What is a non whitespace character in regex?

The \S metacharacter matches non-whitespace characters. Whitespace characters can be: A space character.

What is \d in JavaScript regex?

The RegExp \D Metacharacter in JavaScript is used to search non digit characters i.e all the characters except digits. It is same as [^0-9]. Example 1: This example searches the non-digit characters in the whole string.


1 Answers

In your 2nd character class, \\s will match \ and s, and not \s. Thus it doesn't matches a whitespace. You should use just \s there. Also, move the hyphen towards the end, else it will create unintentional range in character class:

^[^-\s][a-zA-Z0-9_\s-]+$
like image 50
Rohit Jain Avatar answered Sep 28 '22 18:09

Rohit Jain