Bootstrap

【URLSearchParams】优雅的切换站点的多语言

const langMenu = {
    'de': 'Deutsch',
    'en-US': 'english',
    'es': 'español',
    'fr': 'Français',
    'ru': 'Русский',
    'pt': 'portugues',
    'zh-CN': '简体中文',
    'zh-TW': '繁體中文',
}
{/* <Menu>
{Object.keys(langMenu).map(lang => {
  return (
    <Menu.Item key={lang} style={{ width: 140, textAlign: 'center' }} onClick={() => {this.setState({ shareLink: newUrl(shareLink, lang) })}}>
      {langMenu[lang]}
    </Menu.Item>
  )
})}
</Menu> */}
const newUrl = (url, newLang) => {
  const urlObj = new URL(url);
  const searchParams = new URLSearchParams(urlObj.search);
  if (newLang) {
    searchParams.set("lang", newLang);
  } else if (searchParams.has("lang")) {
    searchParams.delete("lang");
  }
  urlObj.search = searchParams.toString();
  return urlObj.href;
};
const res = newUrl("http://xxlb.site/", "pt"); //http://xxlb.site/?lang=pt
console.log(res);
const res2 = newUrl("http://xxlb.site/?lang=zh", "es"); //http://xxlb.site/?lang=es
console.log(res2);
;