Parsing the process of getting the current URL path by JavaScript


This article mainly introduces the JavaScript access to the current URL path analysis process, the article through the example code is very detailed, for everyone’s study or work has a certain reference learning value, need friends can refer to

1. Assume that the full address of the current page is: http://localhost :61768/Home/Index?id=2&age=18

//Gets the URL of the current window
var url = window.location.href;
//Results: the results were as follows http://localhost :61768/Home/Index?id=2&age=18

//Gets the host name of the current window
var host =;
//Results: the results were as follows localhost:61768

//Gets the port of the current window
var port = window.location.port;
//Results: 61768

//Gets the path of the current window
var pathname = window.location.pathname;
//Results: Home / index

//Gets the URL of the current document
var URL = document.URL;
//Results: the results were as follows http://localhost :61768/Home/Index?id=2&age=18

//Get parameters
var search =;
//Results: id = 2 & age = 18

2. Separate parameters in URL

var search =;
Var age = getsearchstring ('age ', search); // result: 18
Var id = getsearchstring ('id ', search); // result: 2
//Key (key to be retrieved) URL (incoming URL address to be split, for example:? Id = 2 & age = 18)
function getSearchString(key, Url) {
  var str = Url;
  str =  str.substring (1,  str.length ); // get the character after "in the URL (remove the first question mark)
  //Separate the string with & to get an element array like name = Xiaoli
  var arr = str.split("&");
  var obj = new Object();

  //Separate each array element with = and assign it to obj object 
  for (var i = 0; i < arr.length; i++) {
    var tmp_arr = arr[i].split("=");
    obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
  return obj[key];

3. Jump out of current window

//Jump out of the current window and open a new one;

4. Document and window

Document implies a document object, and window implies a window object. There can be multiple document objects in a window.

So there is only one window window.location.href , there may be more than one document.URL 、 document.location.href

window.location.href And document.location.href It can be assigned a value and then jump to other pages, document.URL It can only be read but not assigned.

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

Practice of query operation of database table (Experiment 3)

Following the previous two experiments, this experiment is to master the use of select statements for various query operations: single table query, multi table connection and query, nested query, set query, to consolidate the database query operation.Now follow Xiaobian to practice together!Based on the data table (student, course, SC, teacher, TC) created and inserted in […]