MB.
MB.

Reputation: 4211

Why does this line cause Javascript to crash?

This line in Chrome/NodeJS causes it to crash. How come?

In the Chrome, it causes the browser tab to hang with no error message.

"www.asite.com/clothes-intimates-bras-bralettes/sub5-sub6-sub7-sub8".replace(/.*?([\w\s-]*)+\/?$/, 'www.asite.com/product/$1')

Upvotes: 4

Views: 1046

Answers (1)

Paul
Paul

Reputation: 1502

It might help to examine your regular expression in pieces to understand what's going on. Here's the original.

.*?([\w\s-]*)+\/?$

And the breakdown:

.*?

. = anything, * = zero or more, and ? = non-greedy.

([\w\s-]*)+

() = capture, [] = a group, \w = alphanumerics, \s = spaces, - = dashes, * = zero or more, + = one or more.

\/?

? = may or may not occur.

So essentially you're asking to match anything followed by a potentially empty group of charaters, spaces, or dashes which must occur once which is perhaps followed by a slash anchored to the end of the input string. The variable length matches .* and ([\w\s-]*)+ create a potentially infinite set of matches when the regular expression engine starts backtracking.

Your expression matches null (empty string) just as well as it matches -sub8 just as well as it matches www.asite.com/clothes-intimates-bras-bralettes/sub5-sub6-sub7-sub8. Or it could match .*? as nothing, followed by 7000 ([\w\s-] *) captures of nothing (remember * means nothing), then a final ([\w\s-] *) capture of the last character '8'... Sorry to beat on, I'm just trying to get you to an intuitive understanding of the significance of a ([] *)+ style capture.

The expression seems to be a result of not translating exactly what you're intending to match into a regular expression pattern correctly. What were you trying to achieve?

Upvotes: 4

Related Questions