Home > Enterprise >  Google Tag Manager Custom Variable | Extract Selected URL Text
Google Tag Manager Custom Variable | Extract Selected URL Text

Time:11-03

I would like to create a custom variable in Google Tag Manager that extracts a selected part of the URL for me.

Here, it is not a query and the positioning also vary slightly from URL to URL.

An example URL looks like this:

https://website.com?utm_source=google&utm_medium=Organic&utm_content=bathroom&utm_term=shower&utm_campaign=[1_EN]-[1.2_XY]-[4_AB]-[7_Z]

Could you guys maybe help me create a variable that always extracts the text after 1.2_ until the next ]?

In the example: XY

Unfortunately, I've only found solutions online which are based on the assumption that the order of the URL is always identical (and you can use the "split" function) or alternatively it's a query (for example "utm_source").

Unfortunately I don't know JavaScript very well myself.

What I tried so far:

Using split functionality (custom JavaScript variable) Unfortunately the solution is error prone if the URL changes in length or components.

Using query (URL variable). Apparently it doesn't work to query a query in a query - in the case: (1) utm_campaign, (2) 1 = ...

CodePudding user response:

Make a custom JS variable, where you would just have:

function(){
  return {{Page URL}}.split("1.2_")[1].split("]")[0]
}

This should work whenever you have your [1.2_XY] in the url.

This is split-based, which you mentioned you've tried. If this does not work, please post exact url variations for which this should work, but does not.

  • Related