在JavaScript中精确匹配10位数字 [英] Matching exactly 10 digits in Javascript

查看:42
本文介绍了在JavaScript中精确匹配10位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过其他有关SO的问题,但它们似乎并不能为我的问题提供解决方案:

I've tried other questions on SO but they don't seem to provide a solution to my problem:

我具有以下简化的Validate函数

I have the following simplified Validate function

function Validate() {
    var pattern = new RegExp("([^\d])\d{10}([^\d])");

    if (pattern.test(document.getElementById('PersonIdentifier').value)) {
        return true;
    }
    else {
        return false;
    }
}

我已经测试过是否正确检索了该值.但是它与10位数字不完全匹配.我不想要更多或更少.接受10位数字,否则返回false.

I've tested to see if the value is retrieved properly which it is. But it doesn't match exactly 10 digits. I don't want any more or less. only accept 10 digits otherwise return false.

我无法正常工作.尝试以几种方式调整模式,但无法正确进行.也许问题出在其他地方?

I can't get it to work. Have tried to tweak the pattern in several ways, but can't get it right. Maybe the problem is elsewhere?

我在C#中成功完成了以下工作:

I've had success with the following in C#:

Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)")

可接受的示例:

0123456789,1478589654,1425366989

0123456789 ,1478589654 ,1425366989

不可接受:

a123456789,123456789a,a12345678a

a123456789 ,123456789a ,a12345678a

推荐答案

您可以尝试使用 test()函数返回 true/false

You can try with test() function that returns true/false

var str='0123456789';
console.log(/^\d{10}$/.test(str));

或与 String#match()函数一起使用的函数,如果不匹配,则返回 null

OR with String#match() function that returns null if not matched

var str='0123456789';
console.log(str.match(/^\d{10}$/));

注意:只需使用 ^ $ 来匹配整个字符串.

Note: Just use ^ and $ to match whole string.

这篇关于在JavaScript中精确匹配10位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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