最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Change language code in URL using Javascript - Stack Overflow

programmeradmin0浏览0评论

I am developing a website that works in two languages. I need to change URL to include the selected language.

What I exactly need is:

  1. Pick the current URL
  2. Check if the URL contains any language code
  3. Append the code if not exist or change the code to the selected one if exists

For example, there is an URL for English (default):

http://localhost:11767/Home/resultMain?model=1&&type=1

When a user selects Spanish (es) it should be:

http://localhost:11767/es/Home/resultMain?model=1&&type=1

I am developing a website that works in two languages. I need to change URL to include the selected language.

What I exactly need is:

  1. Pick the current URL
  2. Check if the URL contains any language code
  3. Append the code if not exist or change the code to the selected one if exists

For example, there is an URL for English (default):

http://localhost:11767/Home/resultMain?model=1&&type=1

When a user selects Spanish (es) it should be:

http://localhost:11767/es/Home/resultMain?model=1&&type=1
Share Improve this question edited May 11, 2022 at 21:10 Christian 5,5944 gold badges29 silver badges44 bronze badges asked Feb 11, 2017 at 13:03 MoustafaMoustafa 1455 silver badges12 bronze badges 3
  • In which language is your backend written? Are you using node js? – Daniel Commented Feb 11, 2017 at 13:08
  • @Daniel ASP.NET MVC – Moustafa Commented Feb 11, 2017 at 13:08
  • Change window.location? – Jeroen Heier Commented Feb 11, 2017 at 13:09
Add a ment  | 

3 Answers 3

Reset to default 4

You can parse the URL with the help of an a element then replace the part you want and re-build the URL :

function addReplaceLangCode(url, langCode) {
  var a = document.createElement('a');
  a.href = document.getElementById('url').value; // or document.location.href;

  var paths = a.pathname.split('/');
  paths.shift();

  if(paths[0].length == 2) {
    paths[0] = langCode;
  }else{
    paths.unshift(langCode);
  }
  return a.protocol + '//' +
    a.host + '/' + paths.join('/') + 
    (a.search != '' ?  a.search : '') + 
    (a.hash != '' ?  a.hash : '');
}
    
function onClickReplace() {
    document.getElementById('result').innerHTML = addReplaceLangCode( document.location.href, 'es');
}
URL : <input type="text" id="url" style="width:400px" value="http://localhost:11767/Home/resultMain?model=1&&type=1"><input type="button" value="Replace" onclick="onClickReplace()"><br />
Result: <span id="result"></span>

I don't know if it is exactly this, what you want. But JavaScript can obtain URL using object "location". Especially location.pathname is useful for you. You can apply reg-exp on location.pathname to check if URL contain /es/ and if yes, then translate website by proper Ajax requests to your backend.

But generally I remending to use routing of your backend. The best solution in my opinion - use http headers to inform server about preferred language.

https://www.w3/International/questions/qa-accept-lang-locales

Based on @Bulnet Vural's answer above, I wrote the following code because I needed to toggle the language path in and out of the url.

var getOtherLanguageLocation = function (currentUrl, languagePath) {
    // based on https://stackoverflow./a/42176588/1378980
    var anchorTag = document.createElement('a');
    anchorTag.href = currentUrl;
    var paths = anchorTag.pathname.split("/");

    // remove all the empty items so we don't get double slash when joining later.
    var paths = paths.filter(function (e) { return e !== '' })

    // the language will be at index 1 of the paths
    if (paths.length > 0 && paths[0].toLowerCase() == languagePath) {
        // remove the language prefix
        paths.splice(0, 1);
    } else {
        // add the language prefix
        paths.unshift(languagePath);
    }

    return anchorTag.protocol + '//' +
      anchorTag.host + '/' + paths.join('/') +
      anchorTag.search + anchorTag.hash;
};
发布评论

评论列表(0)

  1. 暂无评论