2

I was wondering if anyone knows how to remove an empty query string parameter from Google Analytics?

An example URL would be: http://www.domain.com/index.asp?a=test&b=test&c=&d=test

On this example I would want Google Analytics to filter out "c" because it's empty.

Thanks for any help that can be provided!

3 Answers3

1

It is necessary to differentiate between two methods of implementing GA4 in order to achieve this, either via gtag.js or via Google Tag Manager.

Gtag.js

  • For Google Analytics implemented via gtag.js add the page_location field to the GA4 snippet and give it the cleaned page path
  • note that the code for the cleanPageLocation() function is below
  • add the code e.g. as a ... tag before the GA snippet

        <!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=YOUR- 
       ID-HERE"> 
        </script>
        <script>
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', 'YOUR-ID-HERE', {
            // here the below function goes..
            'page_location': cleanPageLocation(),
          });
        </script>

GTM

If working with Google Tag Manager, you need to add below function to a JavaScript variable and apply it to the page_location field in the GA4 configuration tag:

GA4 exclude query params

Filter out Query Param

  • note that the function only filters out the c parameter as stated
  • if you want to filter out other parameters, then update the excludeStrings array
  • when using this function in GTM, it has to be an anonymous function as per GTMs requirements. Meaning the first line has to be changed to function() {

    function cleanPageLocation() {
    // define parameters to exclude
    var excludeStrings = [
        "c"
    ];
    var addressString = new URL(document.location);
    var queryString = addressString.search;
    
    /* check if query string holds any parameters, otherwise just return the url without them */
    if (queryString.indexOf("?") != -1) {
        /* https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript */
        var getQueryParamsFromURL = function getQueryParamsFromURL() {
            var match,
                search = /([^&=]+)=?([^&]*)/g,
                decode = function decode(s) {
                    return decodeURIComponent(s);
                },
                query = addressString.search.substring(1);
    
            var urlParams = {};
    
            while ((match = search.exec(query))) {
                urlParams[decode(match[1])] = decode(match[2]);
            }
    
            return urlParams;
        };
        // create param object from query string
        var urlParams = getQueryParamsFromURL();
    
        /* if it holds any of the defined parameters, remove the key and keep the rest */
        Object.keys(urlParams).map(function (key) {
            if (excludeStrings.includes(key)) delete urlParams[key];
        });
    
        // Create filtered query string
        var queryString = new URLSearchParams(urlParams).toString();
    
        // add ? to querystring unless it's empty
        if (queryString != "") queryString = "?" + queryString;
    }
    
    // return cleaned URL
        return addressString.origin + addressString.pathname + queryString;
    }

reference: https://bluerivermountains.com/en/ga4-query-parameter-exclusion

0

"http://www.domain.com/index.asp?a=test&b=test&c=&d=test".match(/[^\=\&\?]+=[^\=\&\?]+/g) --JavaScript

should return an array of ["a=test","b=test","d=test"].

Zaq
  • 1,348
  • 1
  • 11
  • 19
0

Expending upon @user1494396; refactor your async tracking code to pass the page name from the regex like so:

(function (window) {
    function cleanQs() {
        if (!window.location.search) {
            return window.location.pathname;
        }
        var locSearchArr = window.location.search.match(/[^\=\&\?]+=[^\=\&\?]+/g);
        var locPathName = window.location.pathname;
        if (locSearchArr && locSearchArr.length > 0) {
            locPathName += "?" + locSearchArr.join("&");
        }
        return locPathName;
    }

    var _gaq = window._gaq || (window._gaq = []);
    window._gaq.push(['_setAccount', 'UA-XXXXX-X']);
    window._gaq.push(['_trackPageview', cleanQs()]);
})(this);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

See:

TomFuertes
  • 7,150
  • 5
  • 35
  • 49