1

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*$/);

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);    

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.