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

问题描述 投票:0回答:1

我的网站上有一个输入字段,我希望当我按下按钮时,在数据被发送到下一个脚本之前,检查该字符串是否符合所需的格式。这应该在JavaScript中实现。例如,格式是 [A-Z][0-9][A-Z]-[0-9][A-Z][0-9]

正确的输入。G7Z-8R4 S3H-1B6

错误的输入:s7Z-b7H sh5T-bs6。

javascript string format
1个回答
0
投票

你可以使用Regex对象的测试方法。

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

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


0
投票
const matches = string.match(/^[A-Z][0-9][A-Z]-[0-9][A-Z][0-9]$/);
© www.soinside.com 2019 - 2024. All rights reserved.