Sven Westerlaken Sven Westerlaken - 5 months ago 14
Javascript Question

Multilangual website - Get specific url part and use this to change the url - JQuery

I am currently working on a navagation bar with a button that let's you change the language of the page.

First of all, I have two subdirectories for each language version of the website:

[...]/en/*.html
[...]/nl/*.html


With *.html standing for every page in that subdirectory

I'm using the same navigation bar on every page so my question is:
How can I swap the middle part of the url using jquery/js?

If it's not possible with Jquery/js, how can I accomplish this without Jquery/js?

Currently I only have the url stored in a variable to use it:

var pathname = window.location.pathname;


which outputs
/en/home.html
(for example)

Easiest way, I think, is to get the /en/ part from the variable, store it another variable and swap the current part with the other language. I know there are a lot of similar questions to this out there, but I can't seem to find an answer to tweak for my usage.

Code requirements:

- Needs to check if it's on the En or Nl version.

- Change the url to the other directory with keeping the *.html intact.

Answer

If you'd like to keep your current structure you can just check if current path is NL or EN and switch for the other one like this:

var pathname = window.location.pathname; //Your page path
var page = pathname.slice(4); //The page name

if (pathname.indexOf("/nl/") >= 0){ //if current page is NL send to EN
    window.location.href = '../en/'+page;
}
else{ //if current page is NOT NL send to NL
    window.location.href = '../nl/'+page;
}
Comments