Skip to content

extractPathname β€” GTM Variable Template for URL

VARIABLES β€Ί URL
extractPathname CORE URL
Direct (.tpl) Apply (.tpl)

Extracts the pathname from a URL.


URL Processing

Parse, build, decode, and manipulate URLs and query parameters.

GA4 Ecommerce

Build and transform ecommerce data structures for GA4 event tracking.

Extraction

Pull specific values, segments, or patterns from complex data structures.


Extract pathname
INPUT
URL: https://example.com/path/to/page
OUTPUT
/path/to/page
Root path returns /
INPUT
URL: https://example.com/
OUTPUT
/

This is what you'll see when you open this variable in Google Tag Manager. Hover the icons for details.

Read-only Preview
extractPathname
URL
πŸ’Ύ The URL to extract the pathname from.

Supported formats:
  βœ“ String
Input Setup
Input Function (optional)
βš™οΈ Optional pre-processing function applied to the input before internal logic (e.g., convert object to string, normalize case). Internal transformations such as case handling will still apply afterward.
Result Handling
Output Function (optional)
βš™οΈ Optional function to apply to the result before returning it (e.g., str => str + ' €', val => val !== undefined for boolean conversion). Useful for chaining transformations on the output.


πŸ“œ View Implementation Code
/**
* Extracts the pathname from a given URL.
*
* @param {string} data.src - The URL to extract the pathname from.
* @param {Function|string} [data.out] - Optional output handler: function to transform result or string with format.
*
* Direct-mode specific parameters:
* @param {Function} [data.pre] - Optional pre-processor function to transform src before extracting.
*
* @returns {string|undefined} The pathname from the URL, or undefined if the input is invalid.
*
* @framework ggLowCodeGTMKit
*/
const parseUrl = require('parseUrl');
const extractPathname = function(url) {
const parsed = parseUrl(url);
return parsed && parsed.pathname || undefined;
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// extractPathname - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const value = applyCast(data.pre, data.src);
return out(extractPathname(value));
// ===============================================================================
// extractPathname() – Apply Mode
// ===============================================================================
/*
return function(value) {
return out(extractPathname(value));
};
*/
πŸ§ͺ View Test Scenarios (5 tests)
βœ… '[example] Extract pathname'
βœ… '[example] Root path returns /'
βœ… URL with query parameters - extracts pathname without query
βœ… Invalid URL - returns undefined
βœ… Empty string input - returns undefined