Alex Turpin Alex Turpin - 5 months ago 21
Javascript Question

Making part of JavaScript regex optional

I have the following original strings:

# Original strings
js/main_dev.js # This one is just to check for false positives

I'd like to run a substitution regex on each one and end up with this:

# Desired result

So basically, add
if it exists, if not, before
. That should only apply on strings that start with
and end in

I initially started out with
as a regex and then
as substitution. That works for my third string, but not my second obviously as I am "hard" looking for
. So I figured I'd make
optional by throwing it in a non capture group with a
like this:
. Now this works for my second string but my third string is all out of whack:

js/main_dev.js # Good
js/blog/foo_dev.js # Good
js/blog/foo.min_dev.js # Bad! _dev should be before the .min

I've tried many permutations on this, including simply doing
but to no avail, all result in the same behavior. Here is a Regex 101 paste with the "bad" regex:

What am I doing wrong here?


Try throwing a ? after the + at the end of your first group (the non-capturing one) to make it non-greedy:


This seemed to fix the issue in the regex101 link you provided. Because (?:\.min)? is optional and .+ is greedy, .+ was capturing the .min.