If you have to, then make sure to do a minimum validation check with less effort before doing the regex part. So, at least if your value does not pass the first check, it will then abort the later checks:
if(// Make sure it is not emptyvalueToCheck&&// Make sure it starts with an `#`valueToCheck[0]==='#'&&// Validate it!valueToCheck.match(/^#([a-f\d]{1,2}){1,2}$/i)){// A hex color code}
JavaScript might not the case but PHP and other templating language performance can be decreased by regular expression and so they can be improved this way.
Although regex is cool, but please try to avoid it where possible. It’s okay for single task but may affect site performance for complex tasks.
For example, your
/^.{8,20}$/
pattern is used to check the length of a string. You can do this instead:If you have to, then make sure to do a minimum validation check with less effort before doing the regex part. So, at least if your value does not pass the first check, it will then abort the later checks:
JavaScript might not the case but PHP and other templating language performance can be decreased by regular expression and so they can be improved this way.
Thank you Bro, yes you can use length, but this is a regex tutorial. Thank you for the advice and discussion.