Today is the second day of Mid-Autumn Festival holiday, so let’s review how to get parameters from URLS. JavaScript does not have a built-in method to get URL parameters. This is a very common requirement that almost every project will use. I wonder if you will write your own in the project, or use ready-made ones?

A modern way

In modern browsers, we can use the URL object provided by the browser to retrieve parameters.

Here is the simplest method, less bugs, we don’t have to worry about.

function getQueryString(name) {
  const url_string = "https://www.baidu.com/t.html?name=mick&age=20"; // window.location.href
  const url = new URL(url_string);
  return url.searchParams.get(name);
}

console.log(getQueryString('name')) // mick
console.log(getQueryString('age')) / / 20
Copy the code

Old cycle method

It works in older browsers without any problems with compatibility, but writing it yourself is cumbersome and can cause bugs.

Of course, you can also find others to write, but there may be a bug pit.

function getQueryString(name) {
  var url_string = "https://www.baidu.com/t.html?name=mick&age=20"; // window.location.href
  var params = url_string.split('? ') [1]; / / get? Name =mick&age=20
  if(! params)return null; // If there is no parameter, null is returned
  var vars = params.split("&"); // Split parameters into arrays ['name= Mick ', 'age=20']
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("="); // Split the key and value into ['name', 'Mick ']
    var key = decodeURIComponent(pair[0]); / / the key parameters
    var value = decodeURIComponent(pair[1]); / / parameter values
    if (name === key) { // Return if the key is matched
      returnvalue; }}return null;
}

console.log(getQueryString('name')) // mick
console.log(getQueryString('age')) / / 20
Copy the code

Regular cycle method

The re implementation also has less code and good compatibility

function getQueryString(name) {
	var query_string = "? name=mick&age=20"; // window.location.search
  if(! query_string)return null; // If there is no parameter, null is returned
  var re = / [&]? ([^=]+)=([^&]*)/g;
  var tokens;
  while (tokens = re.exec(query_string)) {
    if (decodeURIComponent(tokens[1]) === name) {
      return decodeURIComponent(tokens[2]); }}return null;
}

console.log(getQueryString('name')) // mick
console.log(getQueryString('age')) / / 20
Copy the code

conclusion

There are three methods summarized above, of course, there are a lot of methods can be searched on the Internet, as a good front end engineer, we need to understand the principle, try to write.

Feel free to post your thoughts in the comments section and find any bugs I’ve written.