Check if the string starts with one letter followed by numbers (digits) and then any characters

How do I make the below return template true

in scenarios like these:

m1

, m1a

, M100bc

, s45

,S396xyz

and false in scenarios like these:

''

, m

, 1

, 1a

, mm

, Mx

, mm1

,SS1b

Customization template: /^m\S\.*/i.test(text)

It currently accepts any number of letters at the beginning and no numbers right after the first letter

+3


source to share


2 answers


you can use

/^[a-z]\d.*/i

      

See regex demo . If the line may have line breaks, replace .*

with [\s\S]*

.



More details

  • ^

    - beginning of line
  • [a-z]

    - ASCII letter
  • \d

    - digit
  • .*

    - any 0+ characters other than line break characters ( [\s\S]

    will match any characters).

NOTE : .*

(or [\s\S]*

) at the end is only a good idea if you need to use match values. If not, then when used with, RegExp#test()

you can omit this part of the pattern.

+4


source


You can just check only the first two characters.



var cases = ['m1', 'm1a', 'M100bc', 's45', 'S396xyz', '', 'm', '1', '1a', 'mm', 'Mx', 'mm1', 'SS1'];
console.log(cases.map(s => (/^[a-z]\d/i.test(s))));
      

Run codeHide result


+2


source







All Articles