1

In Google Tag Manager, a variable called {{Click URL}} retrieves the full name of the link clicked (http://www.example.com/path/path/file.pdf)

I'm trying to create a variable that will retrieve everything after the last / (file.pdf). I guess I need to create a Custom Javascript variable, but all my attempts so far have failed.

Amongst other things, I tried this solution: Last segment of URL

Code looked something like this:

function () { 
   var href = $(this).attr("href"); 
   window.alert(href.substr(href.lastIndexOf('/') + 1));
   return href;
} 

Also tried this: http://www.apasters.com/blog/google-tag-manager-custom-javascript-variable-examples/

Code looked like this:

function () {
   var value={{Click URL}}.split("/");
   return value[1];
}
Community
  • 1
  • 1
Charles B.
  • 13
  • 1
  • 3

2 Answers2

1

You could try something like this in your custom JS variable:

function(){
   var cu = {{Click URL}};
   var l = cu.split("/").length;
   return cu.split("/")[l-1];
}

This would return the last part of the clicked URL (which is the file name plus extension).

nyuen
  • 8,829
  • 2
  • 21
  • 28
0

There are component types "Query" and "Fragment" in Google Tag Manager also, which would get last part of URL after the ? or #

David
  • 1
  • 1