Justine
Justine

Reputation: 115

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

Upvotes: 0

Views: 256

Answers (1)

bel3atar
bel3atar

Reputation: 943

function() {
  var test1 = 'hello'
  var newURL = new URL(window.location.href)

  if (typeof test1 === 'undefined') {
    newURL.searchParams.append('utm_param', test1);
  }
  return newURL.toString();
}

Upvotes: 1

Related Questions