Javascript Regex替换url中的子目录

时间:2022-05-11 10:25:13

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

我试图匹配特定目录后面的URL中的子目录:

then append a directory to the matched string.

然后将目录附加到匹配的字符串。

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

/ applications / app1应为/ applications / app1 / beta

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

/ applications / app2 /应该是/ applications / app2 / beta /

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

/ applications / app2 / settings应为/ applications / app2 / beta / settings

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

/ applications / app3?q = word应该是/ applications / app3 / beta?q = word

I wrote this:

我写了这个:

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

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

But doesn't work if the app-name is in the end of the string.

但如果app-name位于字符串的末尾,则无效。

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

注意:我没有应用名称我只知道它遵循/ applications /

1 个解决方案

#1


5  

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.

它会在匹配时忽略/ applications / beta。

#1


5  

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.

它会在匹配时忽略/ applications / beta。