我需要知道如何使用javavscript用对象替换urltext。
如果url为www.xyz.com/en/all-services-from-mal-to-sin/details?amount=1000&scy=SGD
,如果lang
为en
,则用匹配的对象密钥替换url,如果lang
为zh
,则用匹配的对象值替换网址。
ExpectedOutput:
if url is
www.xyz.com/en/all-services-from-mal-to-sin?amount=1000&scy=SGD
=> output :www.xyz.com/en/all-services-from-mal-to-sin?amount=1000&scy=SGD
if url is
www.xyz.com/zh/all-services-from-mal-to-sin?amount=1000&scy=SGD
=> output: www.xyz.com/zh/hui-zhi-phi-tho-zmal-zhi-stin?amount=1000&scy=SG
if url is
www.xyz.com/en/hui-zhi-phi-tho-zmal-zhi-stin?amount=1000&scy=SG
=> output: www.xyz.com/en/all-services-from-mal-to-sin?amount=1000&scy=SGD
var obj1={
"transfer-services": "xi-hou-zhi-n",
"about-info": "zhi-zhu",
"contact": "zhi-phi",
"all-services-from": "hui-zhi-phi-tho",
"to": "zhi",
"sin": "stin",
"mal": "zmal"
};
function transformURL(url,value) {
let [base, lang, segment, ...rest] = url.split('/');
lang=value;
if(obj1.hasOwnProperty(segment)) {
segment = obj1[segment];
} else {
Object.entries(obj1).forEach(([key, val]) => {
if(val == segment) {segment = key};
});
}
return [base, lang, segment, ...rest].join('/');
}
console.log(transformURL('www.xyz.com/en/all-services-from-mal-to-sin?amount=1000&scy=SGD', "zh"));
答案 0 :(得分:1)
您拥有的映射是en到zh,如果您想进行2路转换,也需要反向映射。
您的支票obj1.hasOwnProperty(segment)
和val === segment
都将无法使用,因为对象中的所有键都是局部的,段是多个键的组合,因此您需要遍历键,请检查键是否属于该细分市场,然后替换该细分市场的那一部分。
const enToZh = {
"transfer-services": "xi-hou-zhi-n",
"about-info": "zhi-zhu",
"contact": "zhi-phi",
"all-services-from": "hui-zhi-phi-tho",
"to": "zhi",
"sin": "stin",
"mal": "zmal"
};
const zhToEn = Object.keys(enToZh).reduce((a, c) => (
{ ...a, [enToZh[c]]: c }
), {});
function transformURL(url) {
let [base, lang, segment, ...rest] = url.split('/');
const obj = lang === 'en' ? zhToEn : enToZh;
Object.keys(obj).forEach(key => {
segment = segment.replace(key, obj[key]);
});
return [base, lang, segment, ...rest].join('/');
}
console.log(transformURL('www.xyz.com/zh/all-services-from-mal-to-sin/details?amount=1000&scy=SGD'));
答案 1 :(得分:0)
这可能会对您有所帮助。
function transformURL(url,value) {
let [base, lang, segment, ...rest] = url.split('/');
lang=value;
var newsegment=segment.split('?')[0]
if(lang=="zh")
{
newsegment = obj1["all-services-from"]+"-"+obj1["mal"]+"-"+obj1["to"]+"-"+obj1["sin"]+"?"+segment.split('?')[1];
}else{
newsegment = "all-services-from"+"-"+"mal"+"-"+"to"+"-"+"sin"+"?"+segment.split('?')[1];
}
return [base, lang, newsegment, ...rest].join('/');
}