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
3
  • In which language is your backend written? Are you using node js? Commented Feb 11, 2017 at 13:08
  • @Daniel ASP.NET MVC Commented Feb 11, 2017 at 13:08
  • Change window.location? Commented Feb 11, 2017 at 13:09

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

5 Comments

this method will eliminate the part of query string parameters if the url is localhost:11767/es/Home/resultMain?model=1&&type=1 and user click on english the link will be localhost:11767/en/Home/resultMain
Thanks very much it is now working fine and you really save my day :)
Littile bug in this code when the url is localhost:11767/en/Home/resultMain?model=2&type=2 and i click on en agin it will result localhost:11767/en/Home/resultMain/?model=2&type=2 click again on en localhost:11767/en/Home/resultMain//?model=2&type=2 Note the slash that is appended before question mark
Indeed. Please check now. We don't have to add extra '/' before the query string and the hash.
Thanks for the example. Still helpful today. I have replaced '/' with (langCode == '' ? '' : '/') to make it work the other way round.
0

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 recommending to use routing of your backend. The best solution in my opinion - use http headers to inform server about preferred language.

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

Comments

0

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.com/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;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.