Jason Perry
Jason Perry

Reputation: 25

How to get URL values to javascript variable?

How to get parameter value to javascript variable? As an example:

<a href="page.php?id=10&value='hello'">click me</a>

Here, I want to get the key named id, and its value hello to assign them to a javascript variable. How to do it?

Upvotes: 0

Views: 194

Answers (2)

user3459487
user3459487

Reputation: 1

for (let name of document.querySelectorAll("a")) {  
var Reg = /page.php\?id=(\d+)\&value=%27(.*?)%27/g;  
var Array;
while ((Array = Reg.exec(name.href)) != null){
console.log(Array[1]);
console.log(Array[2]);
}  
} 

regex

Upvotes: 0

Daniel Aranda
Daniel Aranda

Reputation: 6552

You may use the URLSearchParams class.

const url_params = new URLSearchParams(window.location.search);
const id = url_params.get('id');
console.log(id);

Upvotes: 1

Related Questions