简体   繁体   中英

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM