Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regular expression match string to start with letter or number

I am trying to see if my string starts with a letter or a number. I think I'm close, could anyone help me out?

if(thestring.match("/^[\pL\pN]/"))
like image 533
bryan Avatar asked May 27 '14 15:05

bryan


People also ask

How do you check if a string starts with a letter JavaScript?

JavaScript String startsWith() The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive.

How do you search for a regex pattern at the beginning of a string?

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.

What does ?= Mean in regular expression?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).


2 Answers

Use:

^[A-Z0-9]

With a case-insensitive modifier:

if(thestring.match(/^[A-Z0-9]/i)) {}

Demo


\pL and \pN are PCRE shortcodes and do not work in Javascript.

like image 62
Sam Avatar answered Oct 01 '22 23:10

Sam


if(/^[a-z0-9]/i.test(thestring)) {
    //do something
}

.test() is much more simple.
It returns just false or true, while .match() resturns null or an array.

More information differences between .test() and .match()

like image 40
Al.G. Avatar answered Oct 01 '22 23:10

Al.G.