Search code examples
javascriptgoogle-tag-manager

Javascript url query string


I'm a newbie to javascript, and I'm trying to create a dynamic variable in Google Tag Manager, I currently have this script

function() {
var test1 = 'hello'
var newURL = window.location.href
  
if (typeof test1!= 'undefined')  
    return newURL;
else
    return newURL + '?utm_param' + test1;
}

With this, I will have output like http://www.test.com/?utm_param=hello

If I want to have a dynamic query string, if the URL ended with test.com/?test1=test&utm_param=hello how do I do that?

Thank you


Solution

  • function() {
      var test1 = 'hello'
      var newURL = new URL(window.location.href)
    
      if (typeof test1 === 'undefined') {
        newURL.searchParams.append('utm_param', test1);
      }
      return newURL.toString();
    }