How to remove query string using Google Tag Manager?

Let's start

Query strings are parameters attached to the actual url to get more information. Query string can be the search terms by the the user or the utm parameters to know the performance of a specific page.  

In order to remove query string using GTM following steps are required

Step#1:  Create a user-define variable which gets the value of Query string. For example name the variable Page Query

 naming variable

naming variable

Step#2: create a custom javascript variable name in for example newPagePath. Here is required code

<script>
  
function() {
      var pageQuery = {{Page Query}};
      var pageURL = {{Page URL}};
      var pagePath = {{Page Path}};

      // remove 'search' query parameter
      var queryResult = pageQuery.replace(/&search(\=[^&]*)?(?=&|$)|^search(\=[^&]*)?(&|$)/, '');
      if(pageURL.indexOf('search=abc') <= -1 && queryResult.length == 0) {
      return pagePath;
      } 
      
      // Add remaining query string to page path
      else {
      if(queryResult.length > 0){
      var newPath = pagePath + "?" + queryResult;
      } 
        
      else {
      // If no query string is present return just page path
      var newPath = pagePath;
      }
      return newPath;
      }
  }

  </script>

Step#3: Implement the javascript variable as Field to set, page variable within all analytics tags

 field to set

field to set

Make sure you have completed the steps carefully in order to get correct reports.

Don't miss out when new resources launch

Our customer analytics experts share wisdom only once a month

Share now
We are customer-analytics consultancy that transforms messy data into actionable insights that will help you grow your company and make better data-backed decisions.