0

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?

  • Does this answer your question? [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – RenaudC5 Nov 08 '22 at 08:41

2 Answers2

1

You may use the URLSearchParams class.

const url_params = new URLSearchParams(window.location.search);
const id = url_params.get('id');
console.log(id);
Daniel Aranda
  • 6,426
  • 2
  • 21
  • 28
  • Not so simple. The value in question is `"page.php?id=10&value='hello'"`, which is an invalid URL search param input. You'll either need some reliable way to get rid of `page.php`, or build the full URL and use the built-in `URL` object. – kelsny Nov 07 '22 at 23:17
0
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