I am pretty noob at JavaScript RegExp. I just need to verify whether a string is 4 characters long and contains only caps letters (A-Z). Any help, highly appreciated.
3 Answers
Quick and dirty way, you can easily do it using:
^[A-Z][A-Z][A-Z][A-Z]$
Snippet
<input id="text" />
<input type="button" onclick="return check();" value="Check" />
<script>
function check() {
var value = document.getElementById("text").value;
if (/^[A-Z][A-Z][A-Z][A-Z]$/.test(value))
alert("Passes");
else
alert("Failed");
}
</script>
Shorter Version
^[A-Z]{4}$
This uses the quantifiers {4}.
Comments
You could use a quantifier as well with a range from A to Z and start and end position of the line.
/^[A-Z]{4}$/
Explanation
/^[A-Z]{4}$/^asserts position at start of the stringMatch a single character present in the list below
[A-Z]{4}{4}Quantifier — Matches exactly 4 timesA-Za single character in the range between A (ASCII 65) and Z (ASCII 90) (case sensitive)$asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

^[A-Z]{4}$should do the job:)