Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25237

Regular Expression for 3 uppercase letter, no more or less

I'm trying to find a regular expression, using Javascript, that will return true when matching 3 letters in uppercase, but it has to be exactly 3, not more or less

Correct:

ASD
WER
ERT

Wrong:

QeW
Q3W
QW
QWER

This is my code, but it also matches 4-letter strings

var r = /[A-Z]{3}/;
r.test("WEE");      //Should return "true"
r.test("WEER");     //Should return "false"

Upvotes: 1

Views: 953

Answers (2)

Stephane Rolland
Stephane Rolland

Reputation: 39906

you should specify the beginning ^ and the end $ of the string in your regexp pattern:

var r = /^[A-Z]{3}$/;

Upvotes: 2

nhahtdh
nhahtdh

Reputation: 56809

You just need to anchor your regex:

var r = /^[A-Z]{3}$/;

^ matches the beginning of the string and $ matches the end of the string. This will force the whole string to match the regex to pass.

Upvotes: 5

Related Questions