Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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( ! ) return;
return location.pathname + (function(){
var i, 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( /^\?$/, '' );

This comment has been minimized.

Copy link
Owner Author

@smhmic smhmic commented Jan 8, 2018

Could improve perf by moving regex out of loop using method shown in this solution -

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment