0

Is it possible to change the content on a webpage based on the URL ?

For example, when someone visits:

example.com/dyanmictextpage.html/?utm_source=google&utm_campaign=dynamictext&utm_term=hello-world

I'd like to update a specific piece of text on the page to then say "Hello World" that's based on the last part of the URL under "utm_term=hello-world"

The code would need to auto insert whatever is after "utm_term=" and remove the hyphen and capitalise the first letters of each word.....

Do you know how??

sean-seamus
  • 11
  • 1
  • 4

2 Answers2

1
var message = '';

var query = document.location.search.substring(1); // Remove leading '?'
var params = query.split('&');

// Get 'utm_term' from the request parameters
for (var i = 0; i < params.length; i++) {
   var key = params[i].split('=')[0];
   if (key === 'utm_term') {
      message = params[i].split('=')[1];
      break;
   }
}

if (message.length > 0) {
   // Split the message by words and capitalize the first letter of each word
   var words = message.split('-');
   for (var i = 0; i < words.length; i++) {
      words[i] = words[i].charAt(0).toUpperCase() + words[i].substring(1);
   }

   // Finally, put the message to HTML (say, to element with id="message")
   document.getElementById('message').innerHTML = words.join(' ');
}
Mikhail
  • 236
  • 2
  • 4
0

You can - a good place to start is to break down your problem into smaller problems, and solve it piece by piece.

The first thing you need to do is get the query string values from the URL (i.e. utm_term=hello-world):

How can I get query string values in JavaScript?

Once you've got those, you'll need to dynamically replace things like hyphens so you can work the data into the format you want:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FString%2Freplace

Once you've done that, you can inject content into the page. I'll leave that bit for you to look up.

Community
  • 1
  • 1
James
  • 13,092
  • 1
  • 17
  • 19