Sep15

Written by:David Aldridge
9/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.

 

Tags:

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

By karting in cardiff on  10/22/2011 3:24 AM

Re: Getting URL parameters and modifying links using Javascript

What am I missing as it doesn't work, the form text box stays empty.

URL:
www.malsforms.com/amy.html?units=2

SCRIPT IN HEAD:


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 unit = getparam('units');
document.form.Totalunit.value=unit;


FORM IN BODY:


Units:

By gt on  7/31/2013 9:39 AM

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment  Cancel 
You must be logged in and have permission to create or edit a blog.