DEV Community

Discussion on: Advanced Regex With Modern Javascript Complete Guide

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman • Edited

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:

let i = valueToCheck.length;
if (i >= 8 && i <= 20) {
    // Passed!
}

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 empty
    valueToCheck &&
    // 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.

Collapse
 
zidniryi profile image
zidniryi

Thank you Bro, yes you can use length, but this is a regex tutorial. Thank you for the advice and discussion.