用/分割网址,并使用javascript替换数据

时间:2019-07-08 04:25:48

标签: javascript arrays object

我想知道如何使用javascript分割url并替换为对象数据。 我有这样的网址

www.xyz.com/en/transfer-services/details
www.xyz.com/en/about-info,
www.xyz.com/en/contact,
www.xyz.com/en/all-services-from-mal-to-sin/details

var obj1={
  "transfer-services": "xi-hou-zhi-n",
  "about-info": "zhi-zhu",
  "contact": "zhi-phi",
  "all-services-from": "hui-zhi-phi-tho",
  "to": "zhi"
}

我有一个按钮,单击后应更改网址为www.xyz.com/en/xi-hou-zhi-n/details,更改为www.xyz.com/en/transfer-services/details,反之-反之亦然。

单击按钮时,如果URL充满英语,则使用obj1键,否则使用obj1值。

1 个答案:

答案 0 :(得分:0)

您可以使用reduce

const urls = [
    "www.xyz.com/en/transfer-services/details",
    "www.xyz.com/en/about-info",
    "www.xyz.com/some/zhi-phi",
    "www.xyz.com/en/all-services-from-mal-to-sin/details"
];

var obj1={
  "transfer-services": "xi-hou-zhi-n",
  "about-info": "zhi-zhu",
  "contact": "zhi-phi",
  "all-services-from": "hui-zhi-phi-tho",
  "to": "zhi",
    "to": "zhi",
    "sin": "stin",
    "mal": "zmal"
};

const output = urls.reduce((accu, url) => {
    let [base, lang, segment, ...rest] = url.split('/');

    if(lang == 'en' && obj1.hasOwnProperty(segment)) {
        segment =  obj1[segment] ;
    } else {
        Object.entries(obj1).forEach(([key, val]) => {
            if(val == segment) { segment = key } ;
        });
    }

    accu.push([base,lang, segment, ...rest].join('/'));
    return accu;
}, []);

console.log(output);

---编辑---

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) {
    let [base, lang, segment, ...rest] = url.split('/');
    if(lang == 'en' && 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/transfer-services/details'));