Getting a URL Parameter
Assuming URL is: http://bfotool.com?size=L&color=red&price=10
var queryString = window.location.search;
console.log(queryString);
// ?size=L&color=red&price=10
Use URLSearchParams to parsing
var urlParams = new URLSearchParams(queryString);
Call any of its methods on the result.
var size= urlParams.get('size')
console.log(size);
// L
var color = urlParams.get('color')
console.log(color);
// red
var price= urlParams.get('price')
console.log(price);
// 10
Checking for the Presence of a Parameter
use URLSearchParams.has()
console.log(urlParams.has('color'));
// true
console.log(urlParams.has('keyword'));
// false
Get all Parameters
var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
var keys = urlParams.keys(),
values = urlParams.values(),
entries = urlParams.entries();
for (const key of keys) {
console.log(key);
}
// size, color, price
for (const value of values) {
console.log(value);
}
// L, red, 10
for(const entry of entries) {
console.log(`${entry[0]}: ${entry[1]}`);
}
// site: L
// color: red
// price: 10