2

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.

2
  • 2
    ^[A-Z]{4}$ should do the job Commented Dec 14, 2016 at 13:38
  • You are welcome! :) Commented Dec 14, 2016 at 13:50

3 Answers 3

4

Quick and dirty way, you can easily do it using:

^[A-Z][A-Z][A-Z][A-Z]$

explanation

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}.

Sign up to request clarification or add additional context in comments.

Comments

2

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 string

      Match a single character present in the list below

      [A-Z]{4}

      {4} Quantifier — Matches exactly 4 times

      A-Z 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)

Comments

0

You could use this:

/^[A-Z]{4}$/.test('your_string')

Example:

var str = 'YEAH';
if(/^[A-Z]{4}$/.test(str)) {
    //true
}
else {
    //false
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.