Friday, July 29, 2011

Read GET parameters using Javascript

Reading get parameters with javascript can't be done using a default function. But it's quiet easy if you play around with window.location.href and some regular expressions. Here is my solution:

function parseGet( name )
{
  name = name.replace(/[\[]/,"\\\[")
  .replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
Usage:
parseGet('getParam');

No comments:

Post a Comment