URL url parameters JSON format into two methods

Before we get into the topic, let me look at methods to get the URL of the URL:

window.location.href // Set or get the entire URL as a string 

window.location.hash // Sets or gets the href attribute parameter section after the # (pound) 

window.location.search // set or get the href attribute with the question mark? Behind the front portion of the well number # parameters

For example, we have here a url, for example: http://127.0.0.1:8080/html/urltojson.html?id=1&name=good#&price=1003

The above three methods below look how to use

console.log(window.location.href);
// http://127.0.0.1:8080/html/urltojson.html?id=1&name=good#&price=1003
console.log(window.location.hash);
// #&price=1003
console.log(window.location.search);
// ?id=1&name=good

 

We see the return parameter is not the same three methods above, if we are going to look to convert url to json format data.

The first: for round-robin fashion

// first: for loop 
var GetQueryJson1 = function () { 
  the let URL = the location.href; // get the current browser the URL 
  the let ARR = []; // array storage parameters 
  let res = {}; // the final result of the object storage JSON 
  arr = url.split ( '?') [1] .split ( '&'); // Get parameter browser address bar 
  
  for (let i = 0; i <arr.length; i ++ ) {// iterate parameters 
    if (arr [i] .indexOf ( '=') = -1) {// if the value of the parameter! 
      the let ARR STR = [I] .split ( '='); 
      RES [STR [0]] = STR [. 1]; 
    } // the else {if no parameter values 
      RES [ARR [I]] = ''; 
    } 
  } 
  return RES; 
} 
the console.log (GetQueryJson1 ());

 

The second: Regular Expressions way

// second: regex 
var GetQueryJson2 = function () { 
  the let URL = the location.href; // get the current browser the URL 
  the let param = {}; // store the final result objects JSON 
  url.replace (/ ( [? ^ &] +) = ([? ^ &] +) / G, function (S, V, K) { 
    param [V] = decodeURIComponent (K); // parse Chinese characters 
    return k + '=' V +; 
  }); 
  return param; 
} 

the console.log (GetQueryJson2 ());

 

JS above is to introduce the small end of the URL url into JSON format approach, we want to help, if you have any questions please give me a message

Guess you like

Origin www.cnblogs.com/wangshucheng/p/11203097.html