Get current URL and modify subdirectory and then go to URL with Javascript

Joseph Mok picture Joseph Mok · Mar 29, 2012 · Viewed 7.9k times · Source

I'm creating a bilingual website for a client. Two versions of the site in different languages will be created and stored in two folders: /en/ /chi/

What I want to do is create a link to toggle between the two languages. On the conceptual level, I understand that Javascript can detect the current URL and split it into its different components, modify parts of it (in this case change between /en/ and /chi/), and then go to that new URL when the link is clicked.

But I have zero knowledge in javascript so I have no idea how to execute... I have come across this page: http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/ but it doesn't explain how to modify and go to the new link.

You help will be greatly appreciated!!

Answer

Chris Calo picture Chris Calo · Mar 29, 2012

To not break usability considerations like Shift + Click to open in a new window, you should create a plain old link (<a>) that points to the other language URL. There's nothing wrong with building the link via JavaScript, but you could also do it on the server using PHP or whatever templating language you're using.

Here's a script that does this with JavaScript if that's what you decide you'd like to do.

<!DOCTYPE html>
<body>
  Content before the link.
  <script>
    (function () {
      // this assumes you're on the en version and want to switch to chi
      var holder = document.createElement("div");
      var url = window.location.href.replace("/en/", "/chi/");
      var link = document.createElement("a");

      link.innerText = "Chewa"; // or whatever the link should be
      link.href = url;
      holder.appendChild(link);
      document.write(holder.innerHTML);
    })();
  </script>
  Content after the link.
</body>