I am pretty noob at JavaScript RegExp. I just need to verify whether a string is 4 characters long and contains only caps letters (AZ). Any help, highly appreciated.
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 (/^[AZ][AZ][AZ][AZ]$/.test(value)) alert("Passes"); else alert("Failed"); } </script>
Shorter Version
^[A-Z]{4}$
This uses the quantifiers {4}
.
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
/^[AZ]{4}$/
^
asserts position at start of the string
Match a single character present in the list below
[AZ]{4}
{4}
Quantifier — Matches exactly 4 times
AZ
a 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)
You could use this:
/^[AZ]{4}$/.test('your_string')
Example:
var str = 'YEAH';
if(/^[A-Z]{4}$/.test(str)) {
//true
}
else {
//false
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.