create a utm in javascript

To create a UTM parameter in JavaScript, you can use the encodeURIComponent() function to safely encode the parameter values.

Here is an example function that takes UTM parameter values as arguments and adds them to the current URL as a query string:

index.tsx
function addUTMParams(source, medium, campaign) {
  // Encode parameter values
  var encodedSource = encodeURIComponent(source);
  var encodedMedium = encodeURIComponent(medium);
  var encodedCampaign = encodeURIComponent(campaign);

  // Get current URL
  var url = window.location.href;

  // Add UTM parameters to URL
  var updatedUrl = url + '?utm_source=' + encodedSource +
                  '&utm_medium=' + encodedMedium +
                  '&utm_campaign=' + encodedCampaign;

  // Update URL in address bar
  window.history.replaceState({path: updatedUrl}, '', updatedUrl);
}
585 chars
18 lines

To use this function, simply call it with your desired UTM parameter values:

index.tsx
addUTMParams('example.com', 'email', 'summer-sale');
53 chars
2 lines

This will add the following query string to the current URL:

index.tsx
?utm_source=example.com&utm_medium=email&utm_campaign=summer-sale
66 chars
2 lines

This UTM parameter can be used for marketing tracking and analytics purposes.

gistlibby LogSnag