user3959525
user3959525

Reputation:

How to verify a string in Javascript using regular expression?

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.

Upvotes: 2

Views: 87

Answers (3)

la3roug
la3roug

Reputation: 311

You could use this:

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

Example:

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

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)

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

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

Upvotes: 4

Related Questions