Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex to replace a sub directory in url

I am trying to match a sub directory in a URL that comes after a specific directory:

then append a directory to the matched string.

/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 doesn't work if the app-name is in the end of the string.

Note: I don't have the app name I only know that it follows /applications/

like image 285
Joe Hany Avatar asked Dec 24 '15 10:12

Joe Hany


1 Answers

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.

like image 75
BGerrissen Avatar answered Sep 18 '22 22:09

BGerrissen