Question

I am trying to redirect the user according to a lang choice drop down and using their current window.location

So if the user is visiting

  1. xxxx.com will need to go to xxxx.com/langchoice. 2.xxxx.com/currentlang/test.php will need to go to xxxx.com/langchoice/test.php 3 xxxx.com/test.php will need to go to xxxx.com/langchoice/test.php

I have done 1 and 2 but not particularly happy with the way that I coded this considering that if more languages might come I need to add a line every time...can this be rewritten better?

var s = window.location.href;

                if (s.indexOf(".php") !=-1) 
                {

                    if (s.indexOf("/en/") !=-1)
                    {
                    var location=window.location.href.replace("/en/","/"+evt.selectedItem+"/");
                    }
                    else if (s.indexOf("/gr/") !=-1)
                    {
                    var location=window.location.href.replace("/gr/","/"+evt.selectedItem+"/");
                    }
                    else if (s.indexOf("/it/") !=-1)
                    {
                    var location=window.location.href.replace("/it/","/"+evt.selectedItem+"/");
                    }
                    else
                    {

                    }

                      window.location.replace(location); 
                }
                else
                {
                    var location=window.location.href.replace("#","");
                    window.location.replace(location+evt.selectedItem); 
                }
Was it helpful?

Solution

This does make the check to see if there is a "language", but the basic idea to replace would be

There are many ways of doing it, this is one way

var orgPathName = window.location.pathname;
var newPathName = orgPathName.replace(/^\/[^\/]*/,"/" + evt.selectedItem);
var newUrl = window.location.href.replace(orgPathName, newPathName);

Now to do the detection, you do a simple test

var hasLang = (/^\/(en|gr|in)\//i).test(window.location.pathname);

pain with this is maintaining the language list

OTHER TIPS

How do you persist langchoice? Do you store it in a cookie?

I think you are essentially saying that the user should be at:

xxxx.com/[langchoice]etc

at all times.

So you could split on '/' and then, if it exists, check item [1]. If it matches the langchoice cookie, continue, if it doesn't, swap it out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top