JSFiddle - React, Tailwind, and code Playground

by Patrick Ludewig

HTML

<a id="application_button" href="https://www.google.com">Hello World</a>

JavaScript

const getUrlParams = (url) => {
  const params = {};
  const urlObj = new URL(url);

  for (const [key, value] of urlObj.searchParams) {
    params[key] = value;
  }

  return params;
};

//const currentUrl = "https://www.aitraining.institute/videos/dein-weg-zum-ai-trainer?first_name=Vera&last_name=Steitz&[email protected]&utm_source=meta&utm_term=Freelancer&utm_content=Kampagne1";
const currentUrl = window.location.href;
const { first_name, last_name, email, utm_source, utm_term, utm_content } = getUrlParams(currentUrl);

const paramsToAppend = [
  { key: 'first_name', value: first_name },
  { key: 'last_name', value: last_name },
  { key: 'email', value: email },
  { key: 'utm_source', value: utm_source },
  { key: 'utm_term', value: utm_term },
  { key: 'utm_content', value: utm_content },
];

const button = document.getElementById('application_button');
const buttonHref = button.getAttribute('href');

const queryParams = paramsToAppend
  .filter(param => param.value !== undefined)
  .map(param => `${param.key}=${encodeURIComponent(param.value)}`)
  .join('&');

const buttonUrl = `${buttonHref}${queryParams ? `?${queryParams}` : ''}`;
button.setAttribute('href', buttonUrl);