[thelist] [JS] regex function vs. plain function

Marcus Andersson marcus at bristav.se
Sun Apr 11 19:22:38 CDT 2004


Joshua Olson wrote:
>>-----Original Message-----
>>From: Tom Dell'Aringa
>>Sent: Friday, April 09, 2004 10:29 AM
>>
>>We're using a function that checks for a valid number entry. It works
>>fine but I am wondering if a regex would be more efficient - it
>>certainly seems it would be smaller. Here is the function:
> 
> 
>>Wouldn't this be better as a regex? We have like 3 or 4 of these...
> 
> 
> Tom,
> 
> Regex's are pretty expensive, so perhaps not.  But, I'd suggest you look at
> performing this same check by using the built-in type casting methods.
> Simply trap the error (using try... catch) so that the method doesn't exit
> out.  If it errors when you try to convert to float or int, then you know
> the value isn't valid.

I wouldn't go that way since parseInt("123ab") would return 123 and 
wouldn't barf at the a and b.

I would go for reg exes if it reduces the amount of code (and therefore 
probably increases readability (that could be put under discussion 
regarding reg exes though) and maintainability) unless it was inside a 
some loop and high performance is crucial.

If it's just about going through some fields and checking them every now 
and then (ie before form submission and not on every key stroke) I would 
surely go for reg exes. If you don't go the reg exp path due to 
performance in such a case I strongly suggest to study the rules of 
optimization.

/Marcus




More information about the thelist mailing list