JavaScript regular expression - two [a-z] followed by three [0-9] only

Scott Brown picture Scott Brown · Dec 2, 2010 · Viewed 23.4k times · Source

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.

Answer

Vlad picture Vlad · Dec 2, 2010

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]?