Written by:David Aldridge9/15/2011 4:07 PM
Most server based languages like PHP and ASP provide simple ways to get to parameters on the URL line. Javascript does not. You need to custom write a function to use regular expressions to extract them from window.location.href. This function will do that: function getparam( paramname ) { paramname = paramname.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexbuild = "[\\?&]"+paramname+"=([^&#]*)"; var regex = new RegExp( regexbuild ); var results = regex.exec( window.location.href ); if( results == null ) return ""; else return results[1]; } You can then extract the parameters using the following type of code:var natscode = getparam('nats'); Where this would extract the parameter nats to natscode. You can then modify the links on the page. This is relatively simple to do in javascript as the document object model maintains a list that can be iterated using a simple for loop:for (i=0; i<document.links.length; i++) { document.links[i].href = document.links[i].href+"?nats="+natscode; }; The above code will take all of the links on a page and append ?nats=<natscode> to them.
function getparam( paramname ) { paramname = paramname.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexbuild = "[\\?&]"+paramname+"=([^&#]*)"; var regex = new RegExp( regexbuild ); var results = regex.exec( window.location.href ); if( results == null ) return ""; else return results[1]; }
var natscode = getparam('nats');
f
or (i=0; i<document.links.length; i++) { document.links[i].href = document.links[i].href+"?nats="+natscode; };
1 comment(s) so far...
Re: Getting URL parameters and modifying links using Javascript I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified.
Re: Getting URL parameters and modifying links using Javascript
I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified.