During the development of the site, small tasks arise, for example, how to extract a parameter from the URL.
For example, we have a URL like this:
http://www.example.com/?page=24&info=13
The parameters in this case are page and info .
To solve this problem, you can use the following code
function getURLParameter(sUrl, sParam) { let sPageURL = sUrl.substring(sUrl.indexOf('?') + 1); let sURLVariables = sPageURL.split('&'); for (let i = 0; i < sURLVariables.length; i++) { let sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam) { return sParameterName[1]; } } }
The first parameter here is the URL from which to retrieve the parameter, and the second parameter is the name of the parameter to be extracted.
This can be useful when you intercept a click event from a link or you just need to extract parameters from the URL in the address bar in the browser.
The application for the above URL will be as follows.
getURLParameter('http://www.example.com/?page=24&info=13', 'page'); getURLParameter('http://www.example.com/?page=24&info=13', 'info');
If you watch the mouse click event, it will look like this
function link_clickHandler(event){ event.preventDefault(); let path = event.target.href; console.log(getURLParameter(path, 'some_parameter'); }