How to remove query string using Google Tag Manager?

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.

Are you looking for a top-notch Data Analytics team to enhance your business’s data-driven decision making? Reach out here or learn why hiring a customer analytics consultant is important for your business? If you want to know more about us, click here.

Share now

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

We're trusted by the best
Need something done?