Here’s a simple way to get a URL parameter with JavaScript:
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('lang') === 'en') {
// Do something.
}
All URL parameters found are available under urlParams
.
We can check a specific parameter using the .get
method.
For example, urlParams.get('lang')
. This returns the value of the lang
parameter if it exists, and null
if not.
If we don’t care about the value of a parameter and we just need to know if it exists in the URL, we can use the .has
method.
For example, urlParams.has('lang')
. This returns a boolean value: true
if the lang
parameter exists and false
if not.
Other methods can be found in MDN: URLSearchParams - Methods.