Reputation: 4585
I'm trying to extract hash substring values from window.location and write them into HTML for the user to see, with an URL syntax that disallows use of ?
as query string delimiter.
Ok, so I have this great code example, thanks to @Gabe:
<html>
<input type="button" id="test" value="Test" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(function() {
$('#test').click(function() {
window.location = (window.location);
GetURLParameter('source');
});
});
function GetURLParameter(sParam) {
var sPageURL = window.location.hash.substring(1);
console.log(sPageURL);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
alert(sParameterName[1]);
return sParameterName[1];
}
}
}
</script>
</html>
I made one modifcatin to his example, so we're using the actual window location from the client ::
window.location = (window.location);
When I hit the "test" submit button on a page containing the above code (the URL is formed like this):
http://example.com/pagename.html#source=FOO&medium=BAR&campaign=FRED
(notice no ?
as query string delimiter, just #
)
... then I get a successful alert, that shows the source "FOO" from the URL. Awesome.
But how to I get the other two SParamaterNames, and then how do I write them into the page as HTML rather than return an alert.
I know this is a basic question for you guys. I'm here because I have been trying to solve this problem for days now, looking at many diff solutions. Any help is greatly appreciated!! thank you very much to all you wizards.
Upvotes: 2
Views: 17736
Reputation: 50493
Just get the hash
value instead of the search
value from the location
object
Here is a working example.
function GetURLParameter(sParam)
{
var sPageURL = window.location.hash.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
Upvotes: 3