简体   繁体   中英

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.
For example the format is:
[AZ][0-9][AZ]-[0-9][AZ][0-9]

Correct Inputs:
G7Z-8R4
S3H-1B6

Wrong Inputs:
s7Z-b7H
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.

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

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

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.

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