mseifert
mseifert

Reputation: 5670

Regex making the browser unresponsive

I have the following regex which works fine at parsing a gradient

/(?:\s*)(?:linear|radial)-gradient\s*\(((?:\([^\)]*\)|[^\)\(]*)*)\)/g

When an invalid string is passed to the regex.exec function like so:

var regex = /(?:\s*)(?:linear|radial)-gradient\s*\(((?:\([^\)]*\)|[^\)\(]*)*)\)/g;
var test = "radial-gradient( circle farthest-corner, white";
regex.exec(test);

The browser hangs with an unresponsive script until it times out.

When I tried this as a regex101, I get a timeout with the message

Your expression took too long to finish and was terminated. Please increase the timeout and try again.

Can you help me rewrite the regex so it won't timeout if it cannot find a match? I, of course, would also like to know why it times out.

Upvotes: 1

Views: 1069

Answers (1)

logi-kal
logi-kal

Reputation: 7880

There is no need to keep a double nested star quantifier:

/(?:\s*)(?:linear|radial)-gradient\s*\(((?:\([^\)]*\)|[^\)\(])*)\)/g

See demo

Upvotes: 2

Related Questions