We can obtain the URL query string with the following Javascript function.
function GET() { var data = []; var param; for(x = 0; x < arguments.length; ++x) { param = location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)"))); if (param == null) { data.push(""); } else { data.push(param[1]); } } return data; }
Try the following example.
<html> <head> <script type="text/javascript"> // Reference: http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript function GET() { var data = []; var param; for(x = 0; x < arguments.length; ++x) { param = location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)"))); if (param == null) { data.push(""); } else { data.push(param[1]); } } return data; } </script> </head> <body> <h1>Hello World</h1> <script type="text/javascript"> // example: http://www.example.com/index.html?name=ykyuen&age=27 alert(GET('name')); // ykyuen alert(GET('age')); // 27 alert(GET('name', 'age')); // ykyuen,27 </script> </body> <html>
The code above is originated from the suggestion by Jet @ Get query string values in JavaScript. i have modified it a bit so it won’t crash if the query string was not found. Thanks Jet.
Done =)
Reference: Get query string values in JavaScript
This is the only code that ever worked for me in WordPress. Thank you so much for this!
LikeLike
good to know that it worked for you. =)
LikeLike
Hey ykyuen,
After some testing several times. It will return whats in the QueryString, but it seems to be cutting off the numbers. I have about an 8 digit ID number that I’m trying to retrieve. It either returns 1, 2, 3, or 5 digits, but never the entire 8.
Any ideas why this might be occurring?
LikeLike
Awesome..worked like a charm…Thanks a TON
LikeLike
You are welcome. Thanks for your comment. =)
LikeLike