• Notice regarding image hosts and attachments. See here.

Quick question: getting URL parameters using Javascript

Soldato
Joined
16 Nov 2003
Posts
9,682
Location
On the pale blue dot
Hey guys. Believe it or not I've never used Javascript but now I have a need to for a static page. Clearly my Google powers are week as I'm not bringing back anything.

Basically if I have the page 'www.example.com/index.html?foo=bar' how can I get the parameter foo and return bar? If this was PHP this would be simple, but I can't find a comparable function in Javascript.

If it helps there will only ever be one parameter, though the variable may contain spaces.
 
Assuming the variables are passed in the url you can retrieve them using window.location, and then parse them.
Code:
<html>
<head>
<script>
function clickMe(){
    alert(window.location);
}
</script>
</head>
<body>
<div id='test' />
<a href="./test.html?foo=bar" onclick="clickMe();return false;">Click</a>
</body>
</html>

Edit: You can also use document.URL :o
 
Last edited:
Thanks, I threw together this, though it seems a little messy:

Code:
document.write(window.location.search.substring(window.location.search.indexOf('=') + 1));
 
Back
Top Bottom