题目
const source_path = "demo/xixi/haha/abc12323.html" // 原始请求url
const math_rule = "/xixi/${_id}/abc${cid}.html$" // 匹配规则
const target_path = "http://127.0.0.1:8001/gg/${cid}/${_id}"; // 目标url
说明:如果匹配的规则命中原始url则将目标url替换成匹配命中的路径,若未命中返回null;上述例子应返回:
http://127.0.0.1:8001/gg/12323/haha
解答
function changeTargetUrl(source_path,math_rule,target_path) {
// 将math_rule中变量进行正则替换 /\/xixi\/(.+)\/abc(.+).html$/
const reg = math_rule.replace('/','\/').replace(/\$\{(.+?)\}/g, '(.+)')
// 从source_path中将变量的值取出
// ["/xixi/haha/abc12323.html", "haha", "12323", index: 4, input: "demo/xixi/haha/abc12323.html", groups: undefined]
const afterPickParams = source_path.match(reg)
if (!afterPickParams) {
return null
}
// 将math_rule中变量提取出来 ["${_id}", "${cid}"]
const pickParams = math_rule.match(/\$\{(.+?)\}/g);
// pickParams循环需要替换的变量,在afterPickParams中找出并替换
for(let key in pickParams){
const targetKey = pickParams[key]
const pickObjIdx = Number(key)+1
target_path=target_path.replace(targetKey, afterPickParams[pickObjIdx])
}
console.log(target_path)
return target_path
}
网友评论