Need to find multiple UTM Paramater present in URL or not

652 views Asked by At

I need to put a condition where in url, if utm parameters are present it should return external campaign or else simple browse. So there are 6 utm parameter which I need to consider, There can be one parameter or multiple parameter in a url at a time. I have used indexOf but I want to URLSearchParams, so can anyone let me know how can apply.

I want to write same logic with URLSearchParams library in JavaScript.

Can anyone please let me know how I can implement.

var a = "";

var url = window.location.href;

if((url.indexOf("utm_source") != -1) || (url.indexOf("utm_campaign") != -1) || (url.indexOf("pkwid") != -1) || (url.indexOf("ep_mid") != -1) || (url.indexOf("et_mid") != -1) || (url.indexOf("ep_rid") != -1))

{

  a= "external campaign";

} else{

    a =  "browse"

}

  

return a;
1

There are 1 answers

0
Twisty On

Consider the following.

function testBrowse() {
  var a = "browse";
  //var url = window.location.href;
  var url = "https://stackoverflow.com/questions/74376327/?pkwid=12&utm_source=home";

  if (url.match(/(?:utm_source|utm_campaign|pkwid|ep_mid|et_mid|ep_rid)/i)) {
    a = "external campaign";
  }

  return a;
}

console.log(testBrowse());

Your logic is not wrong, just not a good practice. It might be better to define the default value and then test if it should be changed.

.match() will return true if the Regular Expression is found.

https://regex101.com/r/5SqVKz/2