Blog

Home > Analytics FAQs > How to remove query string using Google Tag Manager?

How to remove query string using Google Tag Manager?

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.

Share:

Data that Moves Your Business

Connect with Marketlytics

Join 120,000+ Marketers

Stay ahead with expert insights on marketing analysis, data-driven strategies, and industry trends.

Omair

Revenue Growth Analyst
Data Unification Specialist, previously at a leading Ecommerce Giant

Case Studies

Discover our latest success stories
and see how innovative strategies
drive measurable results.

Get a Free Attribution Dashboard

Gain clear insights into what’s
driving conversions and optimize
your marketing spend with ease.

Are you Ready to Fast Track your Marketing Attribution Decisions and Maximize your ROI?

Businesses that leverage automated marketing
attribution see a 20-30% improvement in ad
spend efficiency.