I need to know how to replace the urltext with an object using javavscript.
If the url is www.xyz.com/en/all-services-from-mal-to-sin/details?amount=1000&scy=SGD and if the lang is en, then replace the url with matching object key and if the lang is zh then replace the url with the matching object value.
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"));
ifconditionals or aswitch. You're making this harder than it needs to be.String.replace().