简体   繁体   English

如何检查 JavaScript 中的字符串是否匹配特殊格式?

[英]How can I check if a string in JavaScript matches a special format?

I have an input field on my website and I want that when I press the button that before the data is sent to the next script that the string is checked if it is in the required format.我的网站上有一个输入字段,我希望当我按下按钮时,在将数据发送到下一个脚本之前检查字符串是否为所需格式。 This should happen in JavaScript.这应该发生在 JavaScript 中。
For example the format is:例如格式为:
[AZ][0-9][AZ]-[0-9][AZ][0-9] [AZ][0-9][AZ]-[0-9][AZ][0-9]

Correct Inputs:正确输入:
G7Z-8R4 G7Z-8R4
S3H-1B6 S3H-1B6

Wrong Inputs:错误的输入:
s7Z-b7H s7Z-b7H
sh5T-bs6 sh5T-bs6

const matches = string.match(/^[A-Z][0-9][A-Z]-[0-9][A-Z][0-9]$/);

You can use the test method of Regex object.可以使用Regex object的测试方法。

var pattern = /[A-Z][0-9][A-Z]-[0-9][A-Z][0-9]/;

if(pattern.test(someString)) {
  // someString text matches
}

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

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