so here's the thing: I'm trying to write a code that dynamically constructs regexes to validate phone numbers depending on user input. there can be any number of formats, but the numbers will always be separated by hyphens. The user gets to choose the format, then later the validation runs according to what they have chosen.
Thus:
345-345435 could be valid
as could
2-44444444-44
But I have been finding that constructing the regexes dynamically slows the code down noticeably. For example, if they're hardcoded like this:
Code:
var telformats = {
ph1: (/^(\d{4})-(\d{4})$/), //checks for format of phone number XXXX-XXXX (4 numbers dash 4 numbers)
ph2: (/^(\d{2})-(\d{4})-(\d{4})$/) //checks for format of phone number XX-XXXX-XXXX (2 numbers dash 4 numbers dash 4 numbers)
};
it's almost instantaneous (around 300 millisecs to run the entire validation)
but if I change it to this:
Code:
var inps = document.getElementsByTagName("input")
for (var a = 0; a < inps.length; a++) {
var str = this.value;
var nums = str.split("-")
var exp = "^"
for (var i = 0; i < nums.length; i++) {
exp += "(\\d{" + nums[i].length + "})-"
}
exp = exp.slice(0, -1);
exp += "$";
var reg = new RegExp(exp)
telformats["tel"+a] = reg;
}
it slows it waaaay down, taking about a second longer to run the validation code.
the only real difference that I can see is the use of the new RegExp constructor, but I'm assuming I have to use that because otherwise it's just a string. I even tried the dreaded eval(), but got the same results.
Is there something else I can try?