Skip to content

extractSegmentByIndex — GTM Variable Template for URL

VARIABLES › URL
extractSegmentByIndex CORE URL

Extracts a URL path segment by its index position.


When to Use This

URL Processing

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

Extraction

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


Examples

Extract first segment
INPUT
Pathname: /products/shoes/nike
Segment Index: 0
Remove Trailing Slash: false
Remove Empty Segments: false
Default Value (optional): undefined
OUTPUT
""
Extract middle segment
INPUT
Pathname: /products/shoes/nike
Segment Index: 2
Remove Trailing Slash: false
Remove Empty Segments: false
Default Value (optional): undefined
OUTPUT
shoes

GTM Configuration

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

extractSegmentByIndex
Pathname
💾 The pathname string to extract segment from (e.g., "/products/shoes/nike").

Supported formats:
  ✓ String: path with forward slashes
Segment Index
💾 The zero-based index of the segment to extract. Index 0 is the root (""), index 1 is the first segment after root.

Supported formats:
  ✓ Number: 0, 1, 2, etc.
☑️ If enabled, removes trailing slash from pathname before splitting (e.g., "/products/" becomes "/products").
☑️ If enabled, removes empty segments from the path (except the leading empty string representing root).
Default Value (optional)
💾 The value to return if the index is out of range or the input is invalid.

Supported formats:
  ✓ Any type
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the pathname before extracting segments (e.g., normalize URL, decode URI components).
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the extracted segment before returning it (e.g., str => str.toUpperCase(), str => decodeURIComponent(str)). Useful for chaining transformations on the output.
Pathname string
💡 Type any text to see the result update live
🎯 Using special value — click input to type instead
Test with:
Falsy
Truthy
Segment Index number
Default Value (optional) string
extractSegmentByIndex()


Under the Hood

📜 View Implementation Code
/**
 * Returns a specific segment from a pathname string using its index.
 *
 * @param {string} data.src - The pathname string to extract from (e.g., "/products/shoes").
 * @param {number} data.idx - The index of the segment to return (0-based).
 * @param {boolean} [data.rts=false] - Whether to remove a trailing slash before splitting.
 * @param {boolean} [data.rem=false] - Whether to remove empty segments (except the leading one).
 * @param {*} [data.def] - The default value to return if index is out of range or input is invalid.
 * @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 processing.
 * 
 * @returns {string|*} The path segment at the specified index, or the default value if not found.
 *
 * @framework ggLowCodeGTMKit
 */
const extractSegmentByIndex = function(pathname, index, removeTrailingSlash, removeEmpty, defaultValue) {
    if (typeof pathname !== "string" || typeof index !== "number") {
        return defaultValue;
    }
    
    let normalizedPath = pathname[0] === "/" ? pathname : "/" + pathname;
    
    if (removeTrailingSlash && normalizedPath[normalizedPath.length - 1] === "/") {
        normalizedPath = normalizedPath.slice(0, -1);
    }
    
    let segments = normalizedPath.split("/");
    
    if (removeEmpty) {
        segments = segments.filter(function(segment) { return segment.length > 0; });
        segments.unshift('');
    }
    
    return index >= 0 && index < segments.length ? segments[index] : defaultValue;
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// extractSegmentByIndex - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const value = applyCast(data.pre, data.src);
return out(extractSegmentByIndex(value, data.idx, data.rts, data.rem, data.def));
// ===============================================================================
// extractSegmentByIndex(...) – Apply Mode
// ===============================================================================
/*
return function(pathname, index, removeTrailingSlash, removeEmpty, defaultValue) {
   index = data.rp1 ? data.idx : index;
   defaultValue = data.rp2 ? data.def : defaultValue;
   return out(extractSegmentByIndex(pathname, index, data.rts, data.rem, defaultValue));
};
*/
🧪 View Test Scenarios (10 tests)
✅ '[example] Extract first segment'
✅ '[example] Extract middle segment'
✅ Test with trailing slash removal
✅ Test with index out of range returns default
✅ Test with empty segment removal
✅ Test without leading slash (auto-added)
✅ Test with non-string input returns default
✅ Test with single segment path
✅ Test with root path only
✅ Test last segment extraction