Skip to content

Instantly share code, notes, and snippets.

@cgilchrist
Created February 15, 2011 00:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save cgilchrist/826851 to your computer and use it in GitHub Desktop.
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
<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>
@EvanWillms
Copy link

The replace("+"," ") only converts the first + into a space.
It should be replace(/\+/g," ") to change all of them (using a global regex).

@cgilchrist
Copy link
Author

Updated, thanks Evan!

@hypervelocity
Copy link

I can't seem to get this to handle the %2B in the URLs that come from Google. Any suggestions?

@hypervelocity
Copy link

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