zeshan-a
7/3/2017 - 11:45 AM

Get URL Parameter using JavaScript

Get URL Parameter using JavaScript

/**
 * Get URL Parameter
 *
 * By: Zeshan Ahmed
 * URI: http://www.zeshanahmed.com/
 * Source: stackoverflow (question unknown)
 *
 * This function is used to get the parameter from current URL or 
 * the URL passed via second argument in the function. 
 *
 * Usage: 
 * var searchText = getUrlParameter( 'search' );
 * 
 * @param  {string} sParam    parameter name, e.g., "search"
 * @param  {string} link      (optional) if you want to get the parameter from 
 *                            a different URL then current page url.
 * @return {multiple}         returns the 'value' of parameter
 */
function getUrlParameter( sParam, link ) {
  var sPageURL = ( link ) ? link : decodeURIComponent(window.location.search.substring(1)),
      sURLVariables = sPageURL.split('&'),
      sParameterName,
      i;

  for ( i = 0; i < sURLVariables.length; i++ ) {
    sParameterName = sURLVariables[i].split('=');

    if (sParameterName[0] === sParam) {
        return sParameterName[1] === undefined ? true : sParameterName[1];
    }
  }
};