我已经使用javascript生成了url,它可以正常工作,但需要知道其他替代方法。
通过引用对象替换特定的路径名
var serverobj ={
"about": "about-us",
"info": "get-our-information",
"contact": "contactus"
}
var currenturl = "/en/about" or "/en/contact" or "/en/info-tourspots-cn"
function generateurl(){
var urlpath =currenturl.split("/")[2] ? obj[currenturl.split("/")[2].replace(/-/g, "")]:'';
var redirecturl = window.location.origin+"/"+en+"/"+urlpath;
window.location.href=redirecturl ;
}
所需的输出
// will be /en/about-us for /en/about
// will be /en/contact for /en/contactus
// will be /en/get-our-information-tourspots-cn for /en/info-tourspots-cn
答案 0 :(得分:1)
您可以将以下正则表达式与replace一起使用
(.*\/)([^-]+)(.*)$
var serverobj ={
"about": "about-us",
"info": "get-our-information",
"contact": "contactus"
}
var currenturl = ["/en/about","/en/contact","/en/info-tourspots-cn"]
function generateurl(url){
return url.replace(/(.*\/)([^-]+)(.*)$/g, (_, g1, g2, g3 = '') => {
return g1 + serverobj[g2] + g3
})
}
currenturl.forEach(url => console.log(generateurl(url)) )