Useful Custom JavaScript Variables for Google Tag Manager

Comments:11

  1. Hi
    I need to use a custom js variable to change the name of a data layer product impression variable from ‘style’ to ‘variant’. I also need to add a new variable that is the first 3 characters of another existing variable. I’m trying to work out the JS to write to accomplish these 2 goals.
    thanks

    1. Hi Rebbret,
      To get the first three characters of a variable you can make a custom JS variable like this:
      function(){
      var str = {{your variable}};
      var strFirstThree = str.substring(0,3);
      return strFirstThree;
      }

      I’m not totally sure what you mean about changing the name of the data layer variable. Please clarify with a sample of your code and what you’d like to happen, and I’ll be happy to help further.

  2. Again! This is an amazing post. I’ll link to it in one of my upcoming post on GTM. I am not sure what you can do with the hit timestamp? Can it tell me exactly when a specific tag was fired? If yes, where do you find the information afterwards?

    1. You’re too kind! Yep, the hit timestamp shows exactly when any tag fired. You would see it in a custom dimension later. So for example you could look at the All Pages report, then pull down Secondary Dimension = timestamp, and see exactly when each pageview occurred. It’s a way to disaggregate the standard GA reports.

  3. Hi guys, stupid question but I need to create a custom js variable that calculates revenue minus shipping, Do you know how to write it?
    huge thanks

    1. Hey, it’s not a stupid question. Do you already have variables set up that contain transaction revenue and shipping? If so, your new custom JS variable would look like this (just edit the variable names to match the names you’ve used in your container):
      function(){
      return {{revenue}} - {{shipping}};
      }

      If you don’t have revenue and shipping variables already set up, you can check this post for how to grab those values from an enhanced ecommerce data layer: Collect Enhanced Ecommerce Values into GTM Variables. If you’re using standard ecommerce let me know as the syntax will be a bit different.

Leave a Reply

Your email address will not be published.