• Courses
    • Courses
    • Course bundles
  • Blog
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • Services
  • About
    • About
    • Contact
  • Login
  • Courses
    • Courses
    • Course bundles
  • Blog
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • Services
  • About
    • About
    • Contact
  • Login

May 6, 2025

How to extract part of the URL path with Google Tag Manager

Updated: May 6th, 2025

This blog post might sound similar to the one that I’ve recently published, How to extract a query parameter of the URL, but this time a bit different issue is solved. In that blog post, I was working with query parameters. For example, I was able to fetch the value of productId if the Page URL was https://www.example.com?productId=123.

But in today’s blog post, let’s imagine that we have a URL of the following structure: https://www.example.com/products/category_name/id, and we want to turn the category_name into a GTM variable (knowing that the category name is always in the 2nd subdirectory of the Page Path.

How can we achieve that? Let’s find out.

If you’re not sure what the subdirectory in the URL is, the scheme in this blog post shows it clearly.

Back to our example. In order to access the 2nd subdirectory of the URL, we would need to write a little Custom JavaScript. We’ll try to do that step-by-step so that it would be easier to understand for those who are just starting with JavaScript (disclaimer: I also belong to the group of people who are still starting with JS).

 

Youtube tutorial

If you prefer video content, here’s a tutorial from my Youtube channel.

 

Why would you need this?

Before we dive into the ‘how,’ let’s explore why you might need to isolate specific parts of a URL path using Google Tag Manager. Here are some common scenarios:

  • Content Grouping in GA4: You might want to group content based on a directory in your URL (e.g., /blog/, /products/, /support/). Extracting this part of the path allows you to send it as a custom parameter to GA4 for more meaningful content analysis.
  • Lookup Table Input: The extracted URL part can serve as an input for a Lookup Table variable in GTM, allowing you to map URL segments to more user-friendly names (e.g., /p/123/ becomes ‘Product Category A’).

 

Anonymous JavaScript Function

To extract part of the URL path, we’ll need to use a Custom JS variable. This versatile variable must include a script that meets two criteria:

  • It must be an anonymous function, e.g.  function() { … }
  • It must return some value

Without any hesitation, let’s open a text or code editor (or just the Custom JS editor in the GTM interface) and paste the following code:

function() {
  
}

It will not do anything (but this is just the start of our Custom JS variable).

Now, let’s create a JavaScript variable and name it pageUrl. Then, let’s assign a value to it, window.location.href:

function() {
  var pageUrl = window.location.href;
}

window.location.href is a way to access the current URL of the page where the user/visitor is. In the next step, let’s return that pageUrl but only a part of it. We can do that with the split() method, which splits a string (in this case, URL) into an array of substrings. If you’re new to this, we’ll take a closer look.

Add a return statement to the script (because every Custom JS variable in GTM must return something), then the name of the variable you want to return (pageUrl), and, finally, let’s add a split method.

function() {
  var pageUrl = window.location.href;
  return pageUrl.split();
}

But that’s not all. We need to tell the split() method how exactly we want to split the Page URL. If we go back to our example, we’re working with the https://www.example.com/products/category_name/id (p.s. if you’re trying to follow this along, you can work on some other page where the URL contains some subdirectories).

From that URL, we want to access the category_name. Since it is surrounded by slashes ( / ), which could be used as a delimiter (separator) in our split method, let’s add that slash (surrounded by quotation marks).

function() {
  var pageUrl = window.location.href;
  return pageUrl.split("/");
}

As a result, this will return an array (simply put, a list) of all the parts that are in the URL. Here’s a more visual explanation. Before using the split() method, the Page URL looked like this:

https://www.example.com/products/category_name/id

After using the method, the result visually would look like this:

As you can see above, the URL was split into a list of 6 items, starting with https and ending with the id. The second item in the list is empty (“”) because there was nothing between two slashes in https://.

We’re almost there. category_name has been separated from the URL, all we need to do now is to pick it from this array. This can be done by defining the index of that array member. In our case, that number is 4. If you wanted to fetch the 3rd level of the Page Path (the id), then you should have entered number 5.

Add it right after the split method (surrounded by square brackets):

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

Done! By the way, if you want to learn much more about JavaScript for GTM (and how to write your own code), then take a look at this course.

Subscribe and Get the Ebook - JavaScript for Google Tag Manager

Custom JavaScript variable

Now, let’s paste this code into a Custom JavaScript variable (in the GTM interface). You can name it whatever fits the naming convention of your container, e.g. cjs – 2nd subdirectory of the URL

Save the variable, enable the preview and debug mode and go to the page where you want to test this variable (make sure that the URL contains something in the Page Path (at least 2 levels, a.k.a. folders, a.k.a. subdirectories).

The expected result should look like this (of course, the value will be different in your case).

 

This can be applied to other URLs as well

Don’t limit yourself just to the Page URL. You can apply this to other addresses as well, for example, Click URL, Video URL, etc. You just need to assign another value to the pageUrl variable (in that Custom JavaScript). Here’s an example of how it would look if you wanted to access a certain part of the Clicked URL.

function() {
  var clickUrl= {{Click URL}};
  return clickUrl.split("/")[4];
}

Instead of the window.location.href, we used the Click URL variable of GTM container (just make sure that this built-in variable is enabled in your container). Then the script will take the Click URL, split it (with “/”) and then pick the item of which index if 4.

Keep in mind that the index in JavaScript starts with 0 (zero). Therefore, the 4th element is actually the 5th one.

 

Don’t limit yourself

There are countless use cases where the split() method is really valuable. Imagine that you have a Data Layer variable called {{dlv – productId}} that returns the product id of the following structure — productId-variantId (e.g. 123456-887766) and you want to use only the productId (without a variantId).

In that case, the Custom JS code would look like this:

function() {
  var productId = {{dlv - productId}};
  return productId.split("-")[0];
}

Explanation:

  • I named the var (variable) in the code productId
  • I assigned that var the value of the Data Layer variable {{dlv – productId}}
  • I set the dash ( – ) as a delimiter (separator) because I want to split the product id right where that dash is (reminder: the initial id looks like this 123456-887766)
  • When split() method created an array of two items (123456 and 887766). I chose the first one. In JavaScript, the index number of the first item is 0 (zero), not 1, hence I entered 0.

This variable will return the value of 123456 if the dlv – productId variable’s value is 123456-887766).

 

Extract part of the URL path with Google Tag Manager: Final words

So that’s about it for this fairly short blog post. The split() method is definitely really useful in such tasks when I need to parse a string (usually URL) and fetch a part of it (if the input value always follows the same structure).

If you have any edge cases you’d like to find a solution to, drop me a comment below. Such cases help me learn as well (since I’m still at the very beginning of my JS journey).

Subscribe and Get the Ebook - JavaScript for Google Tag Manager
Julius Fedorovicius
In Google Tag Manager Tips
26 COMMENTS
Markus
  • Aug 14 2019
  • Reply

Nice! I recently set up something very similar to track outbound affiliate links. In addition, I set the value to undefined if there is no value as I've run into issues with GTM not firing the event if there are empty values in the category or action. I also pass the value through another variable/function to format the text as needed:

function() {
var path = {{Click URL}}.split("/go/")[1].split("/");
var product = path[2] !== '' ? path[2] : undefined;

return {{Go Link - Format}}(product);
}

SMG
  • Aug 15 2019
  • Reply

Thanks for this post Julius!
Very useful. I had a recent need for this use case and did something similar.

Jonas
  • Dec 10 2019
  • Reply

If you want to aviod split and only are interested in the whole path

function() {
var url = new URL({{Click URL}})
return url.pathname;
}

    Julius Fedorovicius
    • Dec 10 2019
    • Reply

    If someone is interested in the full click URL path, Custom JS is unnecessary. The same result can be achieved with the following variable:
    - Type: URL
    - Component Type: Path
    - More Settings > URL Source: {{Click URL}}

Mirek
  • Jun 27 2020
  • Reply

Thanks for the entry. Very helpful. I have a question.
I used your script to download a fragment of the url after the sixth "/", but the script gets me too long of the url.
My script looks like this:
function() {
var pageUrl = window.location.href;
return pageUrl.split("/")[6];
}

However, my url downloaded by the script looks like this:

auto23434,Skoda_Octavia-2017

I would like to download only the part of the URL that is up to the comma, which is "auto23434".
Can you help me modify the script?

    Julius Fedorovicius
    • Jun 29 2020
    • Reply

    Hi, the same principle applies as I have explained in this blog post

    function() {
    var pageUrl = window.location.href;
    return pageUrl.split("/")[6].split(',')[0];
    }

Hector
  • Aug 11 2020
  • Reply

Hi Julius. Currently taking your Intermediate GTM Course and finding it very valuable! My question here is how do we split when what we are trying to track is a unique ID that is appended to the END of the url? In other words, the location may change from 3rd to 5th, but it's always at the end.

    Julius Fedorovicius
    • Aug 11 2020
    • Reply

    Between the square brackets, you should enter this:

    pageUrl.split("/").length - 1

    This will return the last index

    The final result could look like this (but of course, you might need to adjust something to your case)

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

bernhard wagner
  • Aug 21 2020
  • Reply

Thanks for the great work, those fierce little pieces can be trouble. I encountered the following:

name-name2-name3 as the result of applying slpit method on page url

I would like to know, how you can get the result 'name name2 name3' (.replace did not work for me)

    Julius Fedorovicius
    • Aug 21 2020
    • Reply

    Replace works only one time. You have 2 dashes.

    Use this temp.split('-').join(' ')

bernhard wagner
  • Aug 21 2020
  • Reply

Worked just fine. Merci

Nishanth
  • Aug 23 2020
  • Reply

Fantastic article, Julius (as always)!

If I can trouble you for some insight for an edge case for the SaaS company that I work at:

- We use only one form for "Request a demo" and "Contact us"
- No matter which Industry or Product you click, it goes to the same /contact-us page.
- My thought was using this URL extraction variable to set up different conversion goals on Analytics. e.g. industry>Request a demo or product>Contact us

    Julius
    • Aug 23 2020
    • Reply

    Try using a referrer variable in GTM.

Hector
  • Aug 28 2020
  • Reply

Hello! I've set this to capture the end of the page path, per your suggestion. Works perfectly except when there are added parameters at the end (specifically, "?glid="). Then, it's grabbing those parameters instead. Is there any way to prevent this?
Thanks for all the help, Julius!

    Julius Fedorovicius
    • Sep 1 2020
    • Reply

    Can you share an example of the URL where this is not working? And also another example where it is working?

      Hector
      • Sep 1 2020
      • Reply

      The URL is dynamic to add a unique identifier (which is what I sought to capture as a custom dimension, named Quote Number) once the page loads. It starts off as "example.com/campaign/?utm=4600" then converts upon loading to something like, "example.com/campaign/543a726c81001". This landing page is being used in a Google Ads campaign with autotagging, so the final result may be something like: "example.com/campaign/543a726c81001?gclid=CjwKCAjwkJj6BRA-EiwA0ZVPViS77Swqm27VVjcP"
      What's odd is that sometimes it captures the string correctly, other times it captures the gclid parameter. It succeeds about 1/4 of the time.

        Julius Fedorovicius
        • Sep 1 2020
        • Reply

        The script would work always if there was always a / in front of the "?gclid=CjwKCAjwkJj6BRA-EiwA0ZVPViS77Swqm27VVjcP"

        My guess is that sometimes the / is added before the question mark and sometimes it is not. And this changes the final result of the script.

        Try playing around with this

        function() {
        var splitPageUrl = window.location.href.split("/")[4];
        if (splitPageUrl.indexOf('?') > -1) {
        return splitPageUrl.split("?")[0];
        }
        }

        Just change the [4] to what you want to access (if it is not working for you now).

Alex
  • Sep 16 2020
  • Reply

Hey Julius, thanks for this post I tried the above-mentioned method

function() {
var splitPageUrl = window.location.href.split("/")[5];
if (splitPageUrl.indexOf('?') > -1) {
return splitPageUrl.split("?")[0];
}
}

But still, some URLs are not in this format for example

/app/account/Register?sourceid=39&campid=2731 -- pagename captured is "Register"

/app/Account/Register?sourceid=587&campid=2581 -- pagename captured is "Register?&sourceid=587&campid=2581"

Any idea why for some it is working while for a few of the same kind of URL's it was not fetching the correct page name

    Julius
    • Sep 16 2020
    • Reply

    That's because there is no / before the ?

    Check the comment that was poated before your comment and you will find a solution.

      Alex
      • Sep 16 2020
      • Reply

      Hi Julius,

      I understand that, as a matter of fact the script I copied it from the previous comment only before my post

      function() {
      var splitPageUrl = window.location.href.split("/")[5];
      if (splitPageUrl.indexOf('?') > -1) {
      return splitPageUrl.split("?")[0];
      }
      }

      as you can see after implementing this most of my page names was getting stored correctly

      Wierd thing is please check below 2 examples both have same url type but one stores the correct page name using this script other one does not

      1.) /app/account/Register?sourceid=39&campid=2731 -- pagename captured is "Register"

      2.) /app/Account/Register?sourceid=587&campid=2581
      -- pagename captured is "Register?&sourceid=587&campid=2581"

      This was my doubt since the script could identify the pagename as Register in the first url but failed somehow for the second

      Could you please have a look

        Julius
        • Sep 16 2020
        • Reply

        Then use

        function() {
        return {{Page Path}} .split("/")[{{Page Path}}.length - 1];
        }

        It will return the last part of the path

Bernhard
  • Dec 7 2020
  • Reply

Hey guys, just another way to retrieve the last part of an URL would be:

function() {
var lastItem = {{Click URL}}.substring({{Click URL}}.lastIndexOf('/') + 1);
return lastItem;
}

//note: other variables like {{Page URL}} or {{PagePath}} are fine with that too

Sibin
  • Nov 9 2021
  • Reply

how to extract a # value [dynamic] from the url (Eg: #confirmation)

    Julius Fedorovicius
    • Nov 10 2021
    • Reply

    Use History Fragment variable and History Change trigger

Andrew
  • Apr 12 2024
  • Reply

I've been using this method for years on GTM and it's worked well. However, recently the developers set a rewrite to remove the trailing slash from all URLs (maybe via htaccess) ... and this stopped working.

Here is my code:

function() {
var output = window.location.href.split("/")[3] ? window.location.href.split("/")[3] : undefined;
return output;
}

So all I am trying to grab is the first directory under the root. I get "undefined" if someone is at "https://example.com/directory"; however, if works fine if someone is at "https://example.com/directory/subdirectory".

In case it helps, I am use the result of this script in a Lookup Table to figure out which GA4, AW and Facebook tag to associate with the visit.

Sébastien
  • May 20 2025
  • Reply

Thanks for tips Julius.
I often use this URL splitting system for multiple purposes. However, if you don't know, i can only advise you to use a variable template available in Template Gallery, in order not to use custom JavaScript (gtm.blocklist) to cut URLs (consulted or clicked split by /), i use "Page Path - Part N" model.

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *


 

Hi, I'm Julius Fedorovicius and I'm here to help you learn Google Tag Manager and Google Analytics. Join thousands of other digital marketers and digital analysts in this exciting journey. Read more
Analytics Mania
  • Google Tag Manager Courses
  • Google Tag Manager Recipes
  • Google Tag Manager Resources
  • Google Tag Manager Community
  • Login to courses
Follow Analytics Mania
  • Subscribe to newsletter
Recent Posts
  • Google Tag Manager Server-Side Tagging with Stape
  • How to Preserve Ad Click IDs with Server-side Tagging
  • LinkedIn Conversions API with Google Tag Manager. The Guide.
Analytics Mania - Google Tag Manager and Google Analytics Blog | Privacy Policy
Manage Cookie Settings