JavaScript regular expression - two [a-z] followed by three [0-9] only
-
30-09-2019 - |
Question
I've got a simple regular expression:
[A-z]{2}[0-9]{3})$/g
inside the following:
regForm.submit(function(){
if ($.trim($('#new-usr').val()).match(/([A-z]{2}[0-9]{3})$/g)) {
alert('No');
return false;
}
});
This is correctly reading that something like 'ab123'
gives an alert and 'ab1234'
doesn't. However, 'abc123'
is still throwing the alert. I need it so it's only throwing the alert when it's just 2 letters followed by three numbers.
Solution
Try /^[A-z]{2}[0-9]{3}$/g
instead.
You need to specify that the whole string needs to be matched. Otherwise you get the highlighted part matched: abc123.
(I omitted the ()
's, because you don't really need the group.)
BTW, are you sure that you want [A-z]
and not just [A-Za-z]
?
OTHER TIPS
The character class [A-z]
is probably not what you need.
Why?
The character class [A-z]
matches some non-alphabetical characters like [
, ]
among others.
JS fiddle link to prove this.
This W3school tutorial recommends it incorrectly.
If you need only lowercase letters use [a-z]
If you need only uppercase letters use [A-Z]
If you need both use: [a-zA-Z]
If you want to match a string if it has 2 letters followed by 3 digits anywhere in the string, just remove the end anchor $
from your pattern:
[a-z]{2}[0-9]{3}
If you want to match a string if it has 2 letters followed by 3 digits and nothing else use both start anchor ^
and end anchor $
as
^[a-z]{2}[0-9]{3}$
Alternatively you can use:
/\b([A-z]{2}[0-9]{3})\b/g
if your string contains multiple words and you are trying to match one word.