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]/"))
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.
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.
?= 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).
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With