I would like to know how to change urlpath based on multiple languages.
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.
how to replace the urltext with an object using javavscript
// for en will receive obj as
{
"transfer-services": "transfer-services",
"about-info": "zhi-zhu",
"contact": "zhi-phi",
"all-services-from": "all-services-from",
"to": "to",
"sin": "sin",
"mal": "zmal"
};
// for zh will receive obj as
{
"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"
};
// for hi will receive obj as
{
"transfer-services": "sabhee sevaen",
"about-info": "baare-mein",
"contact": "sampark-karen",
"all-services-from": "sabhee-sevak",
"to": "se",
"sin": "sg",
"mal": "ml"
}
// will receive above obj base on curr_lang and prev_lang
function translationUrl(langvalue) {
var result = $.ajax({
url: "/" + langvalue,
method: "get",
async: false,
dataType: 'json',
data: {
urllang: langvalue
},
success: function (data) {
return data;
}
}).responseText;
return JSON.parse(result).language.urltext;
}
var prevObj = translationUrl(prev_lang);
var currentObj = translationUrl(curr_lang);
function swapObj(val) {
const lang = Object.keys(val).reduce((a, c) => (
{ ...a, [val[c]]: c }
), {});
return lang;
}
function transformURL(url, curr_lang, prev_lang, prevObj , currObj) { // convert prev to curr lang
let [base, lang, segment, ...rest] = url.split('/');
const obj = lang === prev_lang ? currObj: swapObj(currObj);
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'),"zh", "hi",prevObj , currObj );
Expected outputs:
var prev_lang ="en";
var curr_lang = "hi";
if url is
www.xyz.com/en/all-services-from-mal-to-sin?amount=1000&scy=SGD
=> output :www.xyz.com/hi/sabhee-sevak-ml-to-sg?amount=1000&scy=SGD
var prev_lang ="hi";
var curr_lang = "zh";
if url is
www.xyz.com/hi/sabhee-sevak-ml-to-sg?amount=1000&scy=SGD
=> output :www.xyz.com/zh/hui-zhi-phi-tho-zmal-zhi-stin?amount=1000&scy=SG
var prev_lang ="hi";
var curr_lang = "en";
if url is
www.xyz.com/hi/sabhee-sevak-ml-to-sg?amount=1000&scy=SGD
=> output :www.xyz.com/en/all-services-from-mal-to-sin?amount=1000&scy=SGD
www.xyz.com/zh/all-services-from-mal-to-sin/details?amount=1000&scy=SGD to www.xyz.com/hi/sabhee-sevak-ml-to-sg?amount=1000&scy=SGDbut not work for curr_lang = en and prev_lang =zh ,swapObj()do? And why isobjhardcoded to be eitherhiorswapObj(hi)? Could this be the cause of your problem?swapObjwill reverse the map like { "transfer-services": "sabhee sevaen" } to { "sabhee sevaen" :"transfer-services"} and vive-versa