简体   繁体   中英

iterate over javascript object variables containing regex expressions

I'm wondering if this is possible. I'm trying to iterate over an object containing regex expressions as below:

var formats = {
    AUS:"/^\D*0(\D*\d){9}\D*$/",
    UK: "/^\D*0(\D*\d){9}\D*$/"
        };

    var matched = false;

for (var i in formats) {
    if (!matched) {
        var format = formats[i];
        matched = value.match(formats[i]);
    }
}

I appreciate both AUS & UK expressions are the same value but this is just to prove the concept.

the value I'm matching is 0423887743 and it works when i do the following:

value.match(/^\D*0(\D*\d){9}\D*$/);

Change it to:

var formats = {
   AUS:/^\D*0(\D*\d){9}\D*$/,
   UK: /^\D*0(\D*\d){9}\D*$/
};

The way you have it, it's strings not regular expressions.

string.match takes regular expression as parameter, but you are passing a string.

You can either store regular expressions in your object:

var formats = {
    AUS: /^\D*0(\D*\d){9}\D*$/,
    UK: /^\D*0(\D*\d){9}\D*$/
        };

Or create regular expressions from strings:

var format = new RegExp(formats[i]);
matched = value.match(format);    

I'm not sure why do you need so strange regexp, here is working code:

var formats = {
 AUS:"^0[0-9]{9}$",
 UK: "^0[0-9]{9}$"
};

var matched = false;
var value = '0423887743';
for (var i in formats) {
    if (!matched) {
        var format = formats[i];
        var re = new RegExp(formats[i]);
        matched = ( re.exec(''+value) != null );
    }
}
alert(matched);

NOTE: this code supposes that your format are strings, so you do not need / at the begin and end, if you need them - store without quotes, it will be regexp

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