How to Accurately Retrieve Current Page URL Information in JavaScript

javascript urlwindow.locationget url parametersurl parsingquery string regex
Published·Modified·

In web development, JavaScript is frequently used to retrieve current page URL information. Here is a summary of methods to obtain URL details.

Let's use the following URL as an example to extract its components: http://i.cnblogs.com/EditPosts.aspx?opt=1

1. window.location.href (Set or get the entire URL as a string)

var test = window.location.href;
alert(test);
// Returns: http://i.cnblogs.com/EditPosts.aspx?opt=1

2. window.location.protocol (Set or get the protocol part of the URL)

var test = window.location.protocol;
alert(test);
// Returns: http:

3. window.location.host (Set or get the host part of the URL)

var test = window.location.host;
alert(test);
// Returns: i.cnblogs.com

4. window.location.port (Set or get the port number associated with the URL)

var test = window.location.port;
alert(test);
// Returns: empty string (Note: Even if :80 is added, the return value is an empty string, not the default 80)

5. window.location.pathname (Set or get the path part of the URL, i.e., the file address)

var test = window.location.pathname;
alert(test);
// Returns: /EditPosts.aspx

6. window.location.search (Set or get the part after the question mark in the href attribute)

var test = window.location.search;
alert(test);
// Returns: ?opt=1

PS: Besides assigning values to dynamic languages, we can also use JavaScript to retrieve corresponding parameter values for static pages.

7. window.location.hash (Set or get the fragment after the "#" in the href attribute)

var test = window.location.hash;
alert(test);
// Returns: empty string (since the URL does not contain one)

8. JavaScript Methods to Retrieve URL Parameters

Method 1: Regular Expression Approach

function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}
// Usage:
alert(GetQueryString("param1"));
alert(GetQueryString("param2"));
alert(GetQueryString("param3"));

Method 2: Split Method

function GetRequest() {
  var url = location.search; // Get the string after the "?" in the URL
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }
  return theRequest;
}
var Request = new Object();
Request = GetRequest();
// var id = Request["id"];
// var param1, param2, param3, paramN;
// param1 = Request['param1'];
// param2 = Request['param2'];
// param3 = Request['param3'];
// paramN = Request['paramN'];

Method 3: Specific Parameter Retrieval

For example, given the URL http://i.cnblogs.com/?j=js, if we want to get the value of parameter j, we can use the following function:

function GetQueryString(name) { 
  var reg = new RegExp("(^|&)") + name + "=([^&]*)(&|$)", "i"); 
  var r = window.location.search.substr(1).match(reg); // Get the string after "?" in the URL and match with regex
  var context = ""; 
  if (r != null) 
     context = r[2]; 
  reg = null; 
  r = null; 
  return context == null || context == "" || context == "undefined" ? "" : context; 
}
alert(GetQueryString("j"));

Method 4: Single Parameter Retrieval

function GetRequest() {
  var url = location.search; // Get the string after the "?" in the URL
  if (url.indexOf("?") != -1) {  // Check if there are parameters
   var str = url.substr(1); // Start from the first character since the 0th is "?", get all characters except the question mark
   strs = str.split("=");  // Separate using "=" (since we know there is only one parameter, use "=" directly; if there are multiple, use "&" to separate first, then "=")
   alert(strs[1]);     // Directly pop up the first parameter (if there are multiple parameters, a loop is required)
  }
}

Original source: How to Accurately Retrieve Current Page URL Information in JavaScript - zhabayi. All rights reserved by the original author.