How to Remove Query Parameters From GA Using GTM

Google Analytics builds a unique pageview from the path name and any query string parameters present in the address bar of the browser. Remember, the query string parameters are all the characters after the question mark. Google Analytics strips the hostname / domain name from the URL and the remaining information in the URL becomes a unique page. The query string can be the search terms by the user, filter, sort value or the utm parameters to measure the performance of a specific landing page.

Problems with the URL query parameter

Let’s understand the problem with an example. We have a URL that is http://example.com/analytics-example/. The user lands on this, our analytics example page, and searches for the term ‘analytics solution’ in the internal search bar. But this time the URL would be http://marketlytics.com/analytics-example/?keyword=analytics%20solution. Notice the query string got attached to the URL.

Now, Google Analytics will treat this as a unique pageview for this URL. So instead of displaying a single URL i.e. the actual URL without the query parameter, in the Google Analytics page report you will see both URLs.

How to remove the query parameter through GTM:

Step1: Create a user-defined variable in GTM, which returns the value of Query string. Name the variable Get URL Query. Select ‘Query’ in Component Type. Click Save.how-to-remove-query-parameter-1Step2: After you complete step above, create a custom javascript variable, give a name ‘newPagePath’, for example. Enter the code below in the code editor:

function() {
var q = {{Get URL Query}}.length ? '&' + {{Get URL Query}} : '';
q = decodeURIComponent(q);
var newURL = q.length ? '?' + q.replace(/&[^&@]+@[^&]+/g, '').substring(1) : '';
return newURL.length <= 1 ? '' : newURL;how-to-remove-query-parameter-2The JavaScript function above is a very short and simple regular expression (find and replace), which looks for a query parameter in the URL. If the regular expression finds it, it simply removes the query parameter (or keyword) from the query string, and returns the clean URL without the query parameter.

Step3: In your pageview tag, in Field to set, you will need to add the following:

Field Name: page
Value: {{newPagePath}}how-to-remove-query-parameter-3Make sure you have followed the steps above properly in order to get accurate data in the Google Analytics page report.

If you like my articles,