javascript – Best way to apply a pattern to the acronym

Question:

I have the following possible returns:

  • AB
  • TO 1
  • THE

The first will always be a letter, the second may or may not occur and may be a letter or number. In JavaScript it looks like this (Example):

if (/^[A-Z][\w]$/.test(value.toUpperCase())) {
    callback(true)
} else if(/^[A-Z]$/.test(value.toUpperCase())) {
    callback(true)
} else {
    callback(false)
}

I would like to perform the validation in just one if .

Answer:

The following regex solves your problem simply and without creating unnecessary groups.

/^[A-Z][A-Z0-9]?$/

Explanation:

  • ^ indicates that the occurrence must be at the beginning of the string, otherwise the regex would match xxxA2 ;
  • [AZ] : one character between A and Z
  • [A-Z0-9]? a character between A and Z or between 0 and 9, this character being optional (occurs 0 or 1 time)
  • $ indicates that the occurrence must be at the end of the string, otherwise the regex would match A2xxx ;

Example:

var regex = /^[A-Z][A-Z0-9]?$/;

// Válidos
console.log("A:", regex.test("A"));
console.log("A1:", regex.test("A1"));
console.log("AB:", regex.test("AB"));

// Inválidos
console.log("1:", regex.test("1"));
console.log("A1 :", regex.test("A1 "));
console.log("A-:", regex.test("A-"));
Scroll to Top