Get params from the hash URL by Javascript

Some case, we have to use hash tag in URL to pass a parameter, and we want to get it to use.:

In this example, we do it easily by Javascript.

To start, we write a function call getHashURLParam, and pass a param is param inside:

    function getHashURLParam(param) {
        const hash = window.location.hash.substr(1);
        const params = hash.split('?')[1];
        if (params && params !== '') {
            const prs = params.split('&').reduce(function(res, item) {
                const parts = item.split('=');
                res[parts[0]] = parts[1];
                return res;
            }, {});
            return prs[param];
        }
    }
Copy this code


Usage:

The URL is : https://www.4codev.com/#/?name=xyz&id=xxx

We will call this function and pass param's value 'name' to get value of hash tag is "xyz", the same way if you want to get value of 'id' hash tag.

const name = getHashURLParam('name');
// name = 'xyz'
Copy this code


==