Created
February 15, 2011 00:11
-
-
Save cgilchrist/826851 to your computer and use it in GitHub Desktop.
Replace some text on your page with the value of a URL parameter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
var getUrlParams = function() { | |
var params = {}, hash; | |
var hashes = decodeURI(window.location.href).replace(/\+/g," ").slice(window.location.href.indexOf('?') + 1).split('&'); | |
for (var i=0; i<hashes.length; i++) { | |
hash = hashes[i].split('='); | |
params[hash[0]] = hash[1]; | |
} | |
return params; | |
}; | |
jQuery(function() { | |
// This assumes you have a parameter in your URL called "utm_keyword" | |
var utm_keyword = getUrlParams()['utm_keyword']; | |
if (utm_keyword != undefined) { | |
// This assumes you've given an element on the page and ID of "keyword" | |
jQuery('#keyword').html(utm_keyword); | |
} | |
}); | |
</script> |
Updated, thanks Evan!
I can't seem to get this to handle the %2B in the URLs that come from Google. Any suggestions?
Okay, I figured it out. Pretty good for a non-programmer. Here's what I replaced the second half with. I'm sure it's not ideal, but it seems to work.
jQuery(function() {
// This assumes you have a parameter in your URL called "utm_keyword"
var utm_keyword = getUrlParams()['utm_keyword'];
var utm_keyword = unescape(utm_keyword);
var utm_keyword = utm_keyword.replace(/\+/g, " ");
if (utm_keyword != undefined) {
// This assumes you've given an element on the page and ID of "keyword"
jQuery('#keyword').html(utm_keyword);
}
});
</script>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
replace("+"," ")
only converts the first + into a space.It should be
replace(/\+/g," ")
to change all of them (using a global regex).