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?

1

2 Answers 2

1

You may use the URLSearchParams class.

const url_params = new URLSearchParams(window.location.search);
const id = url_params.get('id');
console.log(id);
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.