简体   繁体   English

如何在jquery中结合正则表达式?

[英]how to combine regex in jquery?

could you please tell me how to combine regex in jquery ?你能告诉我如何在 jquery 中结合正则表达式吗? .I have function to validate mobile number.But I am using three (3) regex I want to combine to one (1). .我有验证手机号码的功能。但我正在使用三 (3) 个正则表达式,我想合并为一 (1) 个。 can we do that我们可以这样做吗

here is my code https://jsbin.com/japokekiji/edit?html,js,console,output这是我的代码https://jsbin.com/japokekiji/edit?html,js,console,output

valid number有效号码

+919313854539

9313854539

09313854539

$(function(){
  var _const ={
     validMobileNumber: ['7777777777', '8888888888', '9999999999']
  }
  $('input').on('keyup',function(){
    console.log(validMobileNumber($(this).val()));
  })
      function validMobileNumber(mobileNumber) {
        var regWithoutZero = /^([7-9])[0-9]{9}$/;
        var regWithZero = /^(0)[7-9][0-9]{9}$/;
        var regWithCountryCode = /^(\+91)[7-9][0-9]{9}$/;
        var isValid = false;
        if (mobileNumber != "" && mobileNumber != null) {
            if (_const.validMobileNumber.indexOf(mobileNumber)!=-1) {
                isValid = false;
            }
            else if (regWithoutZero.test(mobileNumber) || regWithZero.test(mobileNumber) || regWithCountryCode.test(mobileNumber)) {
                isValid = true;
            }
            else {
                isValid = false;
            }
        }
        return isValid;
    }
})

Well it depends, for instance if you want to test with an OR operator, this would be something like this :好吧,这取决于,例如,如果您想使用 OR 运算符进行测试,这将是这样的:

var mergedRegex = /^(([7-9])[0-9]{9}|(0)[7-9][0-9]{9}|(\+91)[7-9][0-9]{9})$/;

If you want with an AND operator, try this instead :如果你想要一个 AND 运算符,试试这个:

var mergedRegex = /^(?=([7-9])[0-9]{9})(?=(0)[7-9][0-9]{9})(?=\+91)[7-9][0-9]{9})$/;

I would go with :我会去:

var mergedRegex = /^(\\+91|0)?[7-9][0-9]{9}$/

I would advise reading up here , if you want to learn all there is to know about regexes.如果您想了解有关正则表达式的所有知识,我建议您阅读此处

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

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