JS - 一个字母和 6 个数字的正则表达式 [英] JS - Regex for one letter and 6 numbers

查看:38
本文介绍了JS - 一个字母和 6 个数字的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个正则表达式来测试输入是否以字母a"开头并后跟 6 个数字.在在线验证器上似乎有效,但在 JavaScript 上无效.

I have this regular expression to test if an input starts with the letter "a" and is followed by 6 numbers. On the online validator seems to work, but on JavaScript doesnt.

这是代码:

function checkBookingReference (ref) {
    var regex = /(^a|A)([0-9]{6})/;
    return regex.test(ref);
}

如果我输入的数字超过六个,该函数返回 true,而它不应该.知道为什么吗?

The function returns true if I enter more than six numbers, and it shouldn't. Any idea why?

推荐答案

如果字符串中的任何地方有匹配项,则该正则表达式将返回 true.如果您想确保 整个 字符串匹配它,那么您需要使用 ^ 匹配开头和 $ 匹配结尾.

That regex will return true if anywhere in the string there is a match. If you want to ensure the entire string matches it, then you'll want to use ^ to match the beginning and $ to match the end.

/^(a|A)([0-9]{6})$/

这篇关于JS - 一个字母和 6 个数字的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆