Question: I had a list of different formats for the string. When a string produces a string of something, the users must key-in the format of that particular string.

If the given string are

> 
> A-01-13A
> 
> 
> (One alphabet, follow by dash, two numbers, follow by dash, two numbers, and one alphabet)
> 
> 
> 

or

> 
> A-01-13
> 
> 
> (One alphabet, follow by dash, two numbers, follow by dash, two numbers)
> 
> 
> 

---

The user's key-in string is **validated** below:

> 
> B-13-99
> 
> 
> B-14-11A
> 
> 
> 

The user's key-in string is **NOT validated** below:

> 
> B-13-100
> 
> 
> 

---

What is the best way to validate the given string using Regex or other methods in Javascript?

Answer: 
The RegExp expression you are looking for is:

```
^([a-zA-Z]{1}-[0-9]{2}-[0-9]{2}[a-zA-Z]{0,1})$

```

This means:
Starts with one character, followed by a dash, followed by two numbers, followed by a dash, followed by two numbers, ends with one or none characters.

You can play with it in [Regex101](https://regex101.com/r/QVzOBB/2) or you can leverage in Javascript as follows:

```js
/** @const {!RegExp} Code pattern to validate. */
const CODE_PATTERN = /^([a-zA-Z]{1}-[0-9]{2}-[0-9]{2}[a-zA-Z]{0,1})$/;

/**
 * Validate that a certain code matches expected RegExp.
 * Uses CODE_PATTERN to validate.
 * @param {string} code - Code to be validated.
 * @return {bool} Whether provided code matches pattern.
 */
const validateCode = function(code) {
  return CODE_PATTERN.test(code);
};

// Test sample of codes.
const testCodes = [
  'A-01-13A',
  'A-01-13',
  'B-13-99',
  'B-14-11A',
  'B-13-100'
];
for (code of testCodes) {
  const isValidCode = validateCode(code);
  console.log(isValidCode);
}
```
you can do it in the following way 

```js
function validate(str){
    return str.match(/^[A-Z]-\d{2}-\d{2}[A-Z]?$/) !== null;
}

console.log(validate('A-01-13A'));
console.log(validate('A-01-13'));
console.log(validate('B-13-99'));
console.log(validate('B-14-11A'));
console.log(validate('B-13-100'));
```