peirix
peirix

Reputation: 37741

finding and replacing parameters in href with javascript

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.

Upvotes: 1

Views: 872

Answers (3)

peirix
peirix

Reputation: 37741

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...

Upvotes: 0

Mark
Mark

Reputation: 108512

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);
            }
        }
    }

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328566

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.

Upvotes: 2

Related Questions