如何解决如何使用替换方法重写URL路径?
我的项目正在使用本地服务器代理。它使用正则表达式将api代理到我的本地文件路径。
这是我的场景:
我的本地http请求是'/ api / bpm / fetch-action-progress-bar?bpm = 123',它将最终找到json文件名'app / data / bpm / fetch-action-progress-bar .json”。
前提条件:仅应重写以'/ api'开头的路径,并且api路径不确定。
实现“ myRegex”来满足以下三个示例:
示例1
'/api/bpm/fetch-action-progress-bar?bpm=123'.replace(myRegex,'app/data/$1.json')
需要:“ app / data / bpm / fetch-action-progress-bar.json”
示例2
'/api/bpm/fetch-action-progress-bar'.replace(myRegex,'app/data/$1.json')
需要:“ app / data / bpm / fetch-action-progress-bar.json”
示例3
'/api/yt/order/export?id=1212'.replace(myRegex,'app/data/$1.json')
需要:“ app / data / yt / order / export.json”
我只能使用replace方法,帮助我实现一个“ myRegex”来解决它。我的困难是查询参数可能不存在。
解决方法
/.*?(?!.*\/)([\w\-]+)[^?]?.*/
使queryparam为'?'
我在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'))
此处的演示和说明: https://regex101.com/r/HBvG3K/10 regex101.com/r/HBvG3K/11
已根据聊天室中的请求进行了更新
\/api\/([\w\-\/]+).*
,
由于此任务不需要采用考虑全局或多行标志的方法,因此像(/\/api\/([^?#]+)[?#]*.*/)
这样的简单正则表达式就已经足够/足够可靠了……请参阅下面满足OP要求的测试...
// see also: [https://regex101.com/r/3mab2d/1]
const regXReplacePath = (/\/api\/([^?#]+)[?#]*.*/);
// example 1
// :: '/api/bpm/fetch-action-progress-bar?bpm=123'
// => 'app/data/bpm/fetch-action-progress-bar.json'
console.log(
'/api/bpm/fetch-action-progress-bar?bpm=123'.replace(
regXReplacePath,'app/data/$1.json'
) === 'app/data/bpm/fetch-action-progress-bar.json'
);
// example 2
// :: '/api/bpm/fetch-action-progress-bar'
// => 'app/data/bpm/fetch-action-progress-bar.json'
console.log(
'/api/bpm/fetch-action-progress-bar'.replace(
regXReplacePath,'app/data/$1.json'
) === 'app/data/bpm/fetch-action-progress-bar.json'
);
// example 3
// :: '/api/yt/order/export?id=1212'
// => 'app/data/bpm/fetch-action-progress-bar.json'
console.log(
'/api/yt/order/export?id=1212'.replace(
regXReplacePath,'app/data/$1.json'
) === 'app/data/yt/order/export.json'
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。