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

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

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;


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

field to set

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