On many occasions I have required to take a value provided by the URL
to carry out an action or simply to print said data to the user without having to go through a server-side language (either Python
, PHP
, Ruby
, among others).
What is the best solution?
In JavaScript there are no intrinsic functions that allow us to obtain the values of GET parameters, as is the case in languages such as PHP that can obtain these values from the global variable
$GET
. Instead, regular expressions can be used to achieve a result that simulates such behavior and obtain an expected value.Solution
In the following url (English) we can get a support function: How can I get query string values in JavaScript?
Quoting the original source of the previous link, we have that:
Use
Taking into account that we have a URL like the following:
The value to obtain would be 88 and we would obtain it with:
Explanation
The getParameterByName function receives a parameter of the type String (text string) that will be used to evaluate by means of a regular expression that searches for all the content between the end of the received string followed by an equals symbol (=) and the end of the string to search for (
location.search
) or until the symbol "et" also known as "ampersand" (&) is found. At the end said text found decoded and returned. In the rare event that no matches are found, it will return an empty string.I have been using the function created by Chris Coyier for some time now , it works very well for me, I have had no problems and it does not use regular expressions:
Example :
URL: http://store.com/shop.php?product_id=32&cat_id=1&sessionid=123
References:
Well this has worked fine for me.
The URLSearchParams interface defines useful methods for working with the search parameters of a URL.
Reference
You can avoid using Regex or similar solutions, by using
URLSearchParams
. You can check out the documentation on MDN for more info on compatibility and more.NOTE: The implemented code may not work in some browsers.
Here at the time I programmed an extension for jquery that gives the parameters both in resful and with unfriendly urls in the readme are the instructions
https://github.com/marcmayol/jquery_extension_url_reader