I am trying to get some custom JS working in Google Tag Manager. What I am trying to do is make it so that anything after an = sign in my outgoing links is tracked as an event in GTM.
For example my links look like this...
https://www.example.org/go/company/?aid=link1
https://www.example.org/go/company/?param=link2
In the urls above I want to capture both "link1" and "link2" as my link id in GTM.
This is the code I am trying to make work with no luck so far. Anyone see what I have wrong?
var link_id = {{Click Path}}.split('=')[1];
if({{Event}}.match(=.*)) return {{Event}};
if(link_id.match(=.*)) return link_id;
return false;
}
Something like:
var link_id = {{Click Path}}.split('=').pop();
return link_id;
This uses split()
to split the {{click Path}} variable at each occurrence of =
sign and then uses pop()
to extract the last element of the resulting array, which is the value after the last =
sign in the URL.
EDIT: Updated the code
var link_id = {{Click Path}}.split('?')[1].split('=')[1];
return link_id;
Now it first uses the split()
method to split the {{Click Path}}
variable at the first occurrence of the ?
character, and then uses a second split()
to split the resulting string at each occurrence of the =
character. The value after the last =
sign in the URL is then extracted by accessing the second element of the resulting array.