The problem is that the regular expression you're using has a pattern that can cause exponential backtracking on certain strings. This means that for some strings, the regular expression engine may end up trying a huge number of possible paths through the pattern, resulting in slow performance and a possible denial of service if an attacker can control the input string.
The part of the expression that's triggering this warning is likely this bit:
([a-z\\d]([a-z\\d-]*[a-z\\d])*)
This pattern is trying to match a series of alphanumeric characters and dashes, but the way it's structured can cause issues. The nested repetition (*
inside of another *
) is what creates the risk of exponential backtracking.
You can usually rewrite the pattern to avoid the nested repetition. In this case, you might rewrite the pattern to something like this:
const validateUrl = str => {
var pattern = new RegExp(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]+[-])*[a-z\\d]+\\.)+[a-z]{2,}|" // domain name
// ... rest of pattern
);
// ... rest of code
}
Here, I've changed the pattern to use ([a-z\\d]+[-])*
to match one or more alphanumeric characters followed by a dash, repeated zero or more times, and then followed by [a-z\\d]+
, which matches one or more alphanumeric characters.
This new pattern should still match valid domain names like the old pattern but without the risk of exponential backtracking. You may want to test it on various inputs to make sure it still behaves as intended.