简体   繁体   English

如何使用正则表达式验证Javascript中的字符串?

[英]How to verify a string in Javascript using regular expression?

I am pretty noob at JavaScript RegExp. 我在JavaScript RegExp上很菜鸟。 I just need to verify whether a string is 4 characters long and contains only caps letters (AZ). 我只需要验证字符串是否为4个字符长并且仅包含大写字母(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} . 这使用了量词{4}

You could use a quantifier as well with a range from A to Z and start and end position of the line. 您也可以使用范围从AZ以及行的开始和结束位置的量词。

/^[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 {4} 量词 -精确匹配4次

      AZ a single character in the range between A (ASCII 65) and Z (ASCII 90) (case sensitive) AZ是介于A(ASCII 65)和Z(ASCII 90)之间的单个字符(区分大小写)

    • $ 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM