get variable from url javascript code example

Example 1: get parameter from the actual url javascript

// https://testsite.com/users?page=10&pagesize=25&order=asc
const urlParams = new URLSearchParams(window.location.search);
const pageSize = urlParams.get('pageSize');

Example 2: javascript read query parameters

// example url: https://mydomain.com/?fname=johnny&lname=depp
const queryString = window.location.search;
console.log(queryString);
// ?fname=johnny&lname=depp

const urlParams = new URLSearchParams(queryString);

const firstName = urlParams.get('fname');
console.log(firstName);
// johnny

const lastName = urlParams.get('lname');
console.log(lastName);
// depp

Example 3: javascript get current url

var currentUrl = window.location.href;

Example 4: javascript get url parameters

let url = 'https://www.example.com?name=n1&name=n2';
let params = (new URL(url)).searchParams;
params.get('name') // "n1"
params.getAll('name') // ["n1", "n2"]

Example 5: how to get variable from url in javascript

var getParams = function (url) {
	var params = {};
	var parser = document.createElement('a');
	parser.href = url;
	var query = parser.search.substring(1);
	var vars = query.split('&');
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split('=');
		params[pair[0]] = decodeURIComponent(pair[1]);
	}
	return params;
};

Example 6: js get url variables

const postID = (new URLSearchParams(window.location.search)).get('post');