Strip URL parameters (GTM Custom JS Variable). Useful for preventing PII from being tracked.
/** | |
* Returns the current page URL with the specified paramaters stripped. | |
* Only includes the path + querystring, as this is intended for overriding `page` field of GA Pageview. | |
* @version 0.1.0 | |
*/ | |
function() { | |
// The params to strip. Case-insensitive. Escape (with a double-backslash) | |
// any regex special chars (unless using regex intentionally). | |
var params = [ 'name', 'email' ]; | |
// You could define the paramaters list as a comma-limited list like this | |
// instead (but ensure there's no space around commas). | |
//var params = 'name,email,phone,address'.split(','); | |
// No paramaters to replace. | |
if( ! location.search ) return; | |
return location.pathname + (function(){ | |
var i, search = location.search; | |
// Remove each specified parameter, regardless of format (p or p= or p=value) or position in the querystring. | |
for( i=0; i<params.length; i++ ){ | |
search = search.replace( new RegExp( '([?&])'+params[i]+'(=[^&]*)?&?', 'gi' ), '$1' ); } | |
// Trim trailing "&"s, and remove "?" if all params removed. | |
return search.replace( /&+$/, '' ).replace( /^\?$/, '' ); | |
})(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Could improve perf by moving regex out of loop using method shown in this solution - https://stackoverflow.com/a/37949642/445295