Javascript Regex replace subdirectory in url

I am trying to map a subdirectory in the url that comes after a specific directory:

then add the directory to the appropriate line.

/applications/app1 should be /applications/app1/beta

/applications/app2/ should be /applications/app2/beta/

/applications/app2/settings should be /applications/app2/beta/settings

/applications/app3?q=word should be /applications/app3/beta?q=word

I wrote this:

path = path.replace(/(\/applications\/(.*)(\/|\s|\?))/, '$1/beta');

But it does not work if the application name is at the end of the line.

Note. I do not have an application name. I only know that it follows /applications/

+6
source share
1 answer
 path.replace(/(\/applications\/[^/?]+)/g,'$1/beta'); 

After some consideration, I prefer the following:

 path.replace(/(\/applications\/[^/?]+)($|\/|\?)(?!beta)/g,'$1/beta$2'); "/applications/app1/beta" -> "/applications/app1/beta" "/applications/app1" -> "/applications/app1/beta" "/applications/app1/settings" -> "/applications/app1/beta/settings" "/applications/app1?q=123" -> "/applications/app1/beta?q=123" 

It will ignore /applications/beta when matching.

+5
source

All Articles