I haven’t written technical articles for a period of time. These days, I happened to encounter a function that I didn’t care too much about before — the front end gets the parameters passed by THE URL

After all, it is usually in the background processing, after losing a pile of hair, I would like to write to share with you, if you encounter a reference in the future

It’s not too hard to just get some regular strings, but there’s a whole bunch of requirements, like passing the same parameter name multiple times, passing an array. It’s just a lot of writing

If you are reading this article to solve a problem, take the Code and use it directly, just read the Code implementation and use it at the end of the article

Use frame thinking to analyze problems

Here’s a URL for you:

NaoNao.com/?product=sh…

Converting the parameters passed in the URL to object objects makes it easier to use the parameters

I have stressed frame thinking many times. Now when we encounter this problem, let’s analyze it with frame thinking. How can we solve it quickly

The first is to understand what is our purpose? The goal is simple: take the parameters passed within the URL and parse them into objects

So what do we know now? A string of the URL

Now, if we get the parameters passed from the URL, what do we do in order to do that?

We all know the characteristics of urls, the first one, right? The strings that follow are all parameters that you pass, but there’s a special case that you should remember, the URL sometimes has a # behind it, and the # behind it is not the parameter that you’re passing, it’s the identifier of the location of the page

If the URL contains #, we just parse it, okay? The string between # and # is ok. If not, what is the first one? All the rest is what we need to parse

You may think I’m talking nonsense, but you don’t have to be an idiot to understand something so obvious

Of course I know, and you don’t have to be an idiot to understand it, but why am I emphasizing it? Because we want to solve problems quickly, we must have a framework thinking, or engineering thinking

Now, you might say, well, does that make sense for such a simple problem? We can see that. You’re just killing me

It may be a waste of time, but if you want to cultivate your engineering thinking, you must keep training until it comes to you

Well, after the analysis, we follow the above ideas to gradually achieve, the realization of the time may encounter other problems, then analyze, and then solve

After all, no matter how awesome an engineer is, he or she will not think about everything before he or she starts work. Instead, he or she can only be thoughtful before he or she starts work and quickly iterate and update when there is a problem

JS The process of getting URL parameters

Get the URL in JS first. If the function takes the URL, use the parameter. If no parameter is passed, the CURRENT page URL is used

var queryString = url ? url.split('? ') [1] : window.location.search.slice(1);
Copy the code

If the string after # is present, we also need to remove the string after #, because the string after # is not the parameter we need to get, but the identifier of the location of the page

queryString = queryString.split(The '#') [0];
Copy the code

Ok, now that we have removed all the interference, we can start parsing the parameters in peace, first dividing the passed parameters into arrays

var arr = queryString.split('&');
Copy the code

Now we can get an array of strings

['product=shirt'.'color=blue'.'newuser'.'size=m']
Copy the code

After splitting the string into arrays, we create an object to store all of our arguments

var obj = {};
Copy the code

We can split a set of arRs into key-value pairs by iterating through them. Make this string a key:value object

var a = arr[i].split('=');
Copy the code

The next step is to assign a value to each variable key. If the value we get is not a correct parameter, we use true to indicate that the parameter name exists. Of course, you can change it according to your own situation

var paramName = a[0];
var paramValue = typeof(a[1= = =])'undefined' ? true : a[1];
Copy the code

I’m just marking undefined here. If it’s NaN, I’m just treating it as a string

There’s a little bit of a little bit of a reminder here, that when we call a function to get the value of an object, if the key passed by the URL is uppercase, and we get the object in lowercase, it’s undefined

For example, if the URL is http://NaoNao.com/?NamE=NaoNao, the value NaoNao can be obtained only when getAllUrlParams().name is called. If the value is processed, we only need to write it all in lowercase/uppercase. Such as getAllUrlParams (). The name

I’m going to change it all to lowercase here, so if you’re case-sensitive, you can remove this Code at that point

paramName = paramName.toLowerCase();
if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();
Copy the code

Next we need to deal with the paramValues we receive, which may be indexed arrays, non-indexed arrays, or regular strings

If it is an indexed array, we need to convert the paramValue to an array and place the value of the index in the corresponding position of the index

If it’s a non-indexed array, we put paramValue in the array

If it’s just a regular string, we need to create a regular attribute for our object obj and assign it a value.

If the key already exists, then we convert the existing paramValue from key:value to an array and place it in the array

Why don’t you take some real examples, get a feel for what we’re doing

// Index the array
getAllUrlParams('http://NaoNao.com/?colors[0]=red&colors[2]=green&colors[6]=blue');
// { "colors": [ "red", null, "green", null, null, null, "blue" ] }

// Non-indexed array
getAllUrlParams('http://NaoNao.com/?colors[]=red&colors[]=green&colors[]=blue');
// { "colors": [ "red", "green", "blue" ] }

// Pass the same key multiple times
getAllUrlParams('http://NaoNao.com/?colors=red&colors=green&colors=blue');
// { "colors": [ "red", "green", "blue" ] }

// Pass key, but not value
getAllUrlParams('http://NaoNao.com/?product=shirt&color=blue&newuser&size=m');
// { "product": "shirt", "color": "blue", "newuser": true, "size": "m" }
Copy the code

I’m using regular expressions to make this judgment, so I won’t explain the re here… After all, it’s too long to explain, so read as much as you can

What does each re parse? There are examples in the comments. If you know a little about regular expressions, you can probably understand them

The corresponding code implementation is as follows:

// if paramName ends with square brackets, e.g. colors[] or colors[2]
if (paramName.match(/\[(\d+)?\]$/)) {
    // If paramName does not exist, create a key
    var key = paramName.replace(/\[(\d+)?\]/.' ');
    if(! obj[key]) obj[key] = [];E.g. colors[2]
    if (paramName.match(/\[\d+\]$/)) {
        // Get the index value and add the value at the corresponding position
        var index = /\[(\d+)\]/.exec(paramName)[1];
        obj[key][index] = paramValue;
    } else {
        // If it is any other type, put it in the arrayobj[key].push(paramValue); }}else {
    // Handle string types
    if(! obj[paramName]) {// If paramName does not exist, create a property of the object
        obj[paramName] = paramValue;
    } else if (obj[paramName] && typeof obj[paramName] === 'string') {
        // If the attribute exists and is a string, then it is converted to an array
        obj[paramName] = [obj[paramName]];
        obj[paramName].push(paramValue);
    } else {
        // If it is any other type, throw it into the arrayobj[paramName].push(paramValue); }}Copy the code

If your URL’s pass parameter contains special characters, such as Spaces. For example, url=”NaoNao.com/?name=Nao%20Nao”, once you get the object value, you need to decode it to get the correct value

var original = getAllUrlParams().name; // 'Nao%20Nao'
var decode = decodeURIComponent(original); // 'Nao Nao'
Copy the code

Specific implementation and use

Below is the complete implementation of JS, you can copy back to use

function getAllUrlParams(url) {
    // Get the URL with JS. If the function receives the URL, use the function's arguments. If no parameter is passed, the CURRENT page URL is used
    var queryString = url ? url.split('? ') [1] : window.location.search.slice(1);
    // To store all of our parameters
    var obj = {};
    If no parameter is passed, an empty object is returned
    if(! queryString) {return obj;
    }
    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split(The '#') [0];
    // Divide the parameters into arrays
    var arr = queryString.split('&');
    for (var i = 0; i < arr.length; i++) {
        // Split into key:value
        var a = arr[i].split('=');
        // mark undefined as true
        var paramName = a[0];
        var paramValue = typeof (a[1= = =])'undefined' ? true : a[1];
        // Delete these two lines of code if case sensitive is required when calling objects
        paramName = paramName.toLowerCase();
        if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();
        // if paramName ends with square brackets, e.g. colors[] or colors[2]
        if (paramName.match(/\[(\d+)?\]$/)) {
            // If paramName does not exist, create a key
            var key = paramName.replace(/\[(\d+)?\]/.' ');
            if(! obj[key]) obj[key] = [];E.g. colors[2]
            if (paramName.match(/\[\d+\]$/)) {
                // Get the index value and add the value at the corresponding position
                var index = /\[(\d+)\]/.exec(paramName)[1];
                obj[key][index] = paramValue;
            } else {
                // If it is any other type, put it in the arrayobj[key].push(paramValue); }}else {
            // Handle string types
            if(! obj[paramName]) {// If paramName does not exist, create a property of the object
                obj[paramName] = paramValue;
            } else if (obj[paramName] && typeof obj[paramName] === 'string') {
                // If the attribute exists and is a string, then it is converted to an array
                obj[paramName] = [obj[paramName]];
                obj[paramName].push(paramValue);
            } else {
                // If it is any other type, throw it into the arrayobj[paramName].push(paramValue); }}}return obj;
}
Copy the code

How do I use this function?

Call the URL argument as an object

Take the URL at the beginning of the article as an example

// http://NaoNao.com/?product=shirt&color=blue&newuser&size=m#Hello

getAllUrlParams().product; // 'shirt'
getAllUrlParams().color; // 'blue'
getAllUrlParams().newuser; // true
getAllUrlParams().NB; // undefined
getAllUrlParams('http://NaoNao.com/?NaoNao=shuai').NaoNao; // shuai
Copy the code

Incompatible with IE solutions

If we don’t need to worry about Internet Explorer and some very old browsers, use the URLSearchParams interface in the browser… This interface can take parameters directly from the URL

// URL is http://NaoNao.com/?product=shirt&color=blue&newuser&size=m
const urlParams = new URLSearchParams(window.location.search);
// Check whether the parameter exists
console.log(urlParams.has('product')); // true
// Get the corresponding value of the parameter
console.log(urlParams.get('product')); // "shirt"
Copy the code

This interface also provides more sophisticated methods such as keys(),Values() and entries(). How to use this interface? Just read the official documentation

Wechat scan code concern public account “Nao Nao Eat fish”, every week has good sharing, but also can receive learning resources oh ~ not only technology!