tags:

views:

115

answers:

3

Here's the issue:

I need to check for a parameter in the query. If it's been set, then I need to change it (harder part). If it hasn't been set, I need to set it (easy part)

I was so sure it would be an easy task, but it somehow ended up being a bit more complicated than I thought. Especially for those cases where there are multiple parameters, and the one I'm looking for is in the middle somewhere.

The parameter is "siteLanguage", and is always followed by =xx where xx represents any two characters, like en or es or whatever. So maybe regex is the answer (boy, do I suck at regex)

No frameworks for this one, guys, just plain ol' javascript.

+2  A: 

I guess you've figured out how to find all the links.

The standard format of an URL is service://host/path?query

I suggest to cut away the query (just take everything after the first ?) and then split that at & (because that separates parameters).

You'll be left with an array of the form key=value. Split that into an associative array. Now you can work on that array. After you've made your modifications, you need to join the query again and set the href attribute of the link.

Aaron Digulla
That sounds pretty waterproof. But a bit too complicated when only looking for _one_ parameter, and even knowing the name of it. This would be better for a general function, though, I think.
peirix
+1  A: 

This would check all "a href=" throughout the document appending or adjusting the language.

checkhrefs = function(lang){
        var links = document.getElementsByTagName("a");
        for (var i=0;i<links.length;i++){
         if (links[i].href.indexOf("siteLanguage") == -1){
          links[i].href += "&siteLanguage="+lang;
         } else {
          links[i].href = links[i].href.replace(new RegExp("siteLanguage=[a-z][a-z]"),"siteLanguage="+lang);
         }
        }
    }
Mark
And I see now that's not what you need at all, lol.
Mark
Hehe. No, but I do like your regex. Which might be quicker than doing indexOf + substring + replace...
peirix
A: 

Ended up just doing a quick hack like so:

function changeLanguage(lang) {
   if (location.search.indexOf("siteLanguage") > -1) { //siteLanguage set
      location.href = location.search.replace(/siteLanguage=[a-z][a-z]/, "siteLanguage="+lang);
   } else if (location.search == "") {
      location.href += "?siteLanguage="+lang;
   } else {
      location.href += "&siteLanguage="+lang;
   }
}

Actually pretty happy with a 9-liner function...

peirix