Extracting URL Strings Into Google Tag Manager

I’ve been teaching myself JavaScript in the last few weeks to up my GTM implementation skills, so I thought I’d share some examples of how I’ve used it.

This one is for pulling out the sub-directory from the URL to use in an event. This came in handy for me when implementing Mixpanel a couple months ago for a client, and is especially helpful for sites that have a solid directory structure. For instance, the shoes page on an eCommerce clothing site might look something like this:

example.com/men/shoes/sneakers/the-new-lebrons/

If you want to create an event for all of the category pages, it’s helpful to be able to pull out “sneakers” and use it in a property so that you can compare it to events with the property of “dress-shoes” and “sandals”.

I created a Custom JavaScript variable in GTM and here’s the code I used:

1
2
3
4
function () {
var value={{Page Path}}.split("/");
return value[1];
}

This pulls out the 2nd sub-directory (‘shoes’ in this case) and stores it in a GTM variable. You can change which directory level gets pulled by changing the [1] to [0] or [2] or whatever (the counting always starts with 0).

Here’s a screen shot of the custom variable in GTM:

Google Tag Manger URL parsing screenshot

google tag manager, javascript