Custom Javascript GTM variable - remove UTMs

Viewed 26

I've got a CSJ variable to capture the last parameter of the URL. Given I'm interested on capturing the location and its position may vary (see example below), I managed to create a custom variable that will always give me the last parameter in the URL.

URL examples: https://www.example.co.nz/location/**holmwood**

https://www.example.co.nz/find-a-location/auckland/**central-auckland**

The issue I'm having is that my script (see below) is not only capturing the last parameter of the URL, but any string after the "?" symbol, which are mainly UTMs.

Code:

function(){
  var pageUrl = window.location.href;
  return pageUrl.split("/")[pageUrl.split("/").length - 1];
}

So, on my GA view instead of seeing the ph + the location, I see a large string:

enter image description here

I know I could use page path and remove query from there, but for a specific event I'd rather sort that out from the custom variable because of the type of value I'm passing.

What else should I add to my script to keep it completely the same and exclude any query parameters that might be automatically tagged?

Thanks.

1 Answers

Rather than returning the first split, I would then put it through an additional one where you are splitting on the '?'

function(){
var pageUrl = window.location.href;
var lastSlash = pageUrl.split("/")[pageUrl.split("/").length - 1];
return lastSlash.split("?",1);
}
Related