Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use replace method to rewrite a url path?

My project is using local server proxy. It proxys an api to my local file path by using regex.

Here is my scene:

My local http request is '/api/bpm/fetch-action-progress-bar?bpm=123' and it will finally find the json file name of 'app/data/bpm/fetch-action-progress-bar.json'.

Precondition: only the path begins with '/api' should be rewritten And the api path is uncertain.

Realizing a 'myRegex' to satisfy the three examples below:

example 1

'/api/bpm/fetch-action-progress-bar?bpm=123'.replace(myRegex, 'app/data/$1.json')

wanted: 'app/data/bpm/fetch-action-progress-bar.json'

example 2

'/api/bpm/fetch-action-progress-bar'.replace(myRegex, 'app/data/$1.json')

wanted: 'app/data/bpm/fetch-action-progress-bar.json'

example 3

'/api/yt/order/export?id=1212'.replace(myRegex, 'app/data/$1.json')

wanted: 'app/data/yt/order/export.json'

I can only use replace method, help me to realize a 'myRegex' to solve it. My difficulty is the query parameters may not existing.

like image 575
Jon003 Avatar asked Nov 30 '25 03:11

Jon003


1 Answers

/.*?(?!.*\/)([\w\-]+)[^?]?.*/

Made the queryparam '?' optional.

I checked this in jsfiddle.net

console.log('/api/bpm/fetch-action-progress-bar?bpm=123'.replace(/.*?(?!.*\/)([\w\-]+)[^?]?.*/, 'app/data/$1.json'))  

console.log('/api/bpm/fetch-action-progress-bar'.replace(/.*?(?!.*\/)([\w\-]+)[^?]?.*/, 'app/data/$1.json')) 

Demo and explanation here: https://regex101.com/r/HBvG3K/10 regex101.com/r/HBvG3K/11

Updated as per the request in the chat

\/api\/([\w\-\/]+).*
like image 148
rootkonda Avatar answered Dec 02 '25 18:12

rootkonda