Skip to content

extractHostname — GTM Variable Template for URL

VARIABLES › URL
extractHostname CORE URL

Extracts the hostname from a URL (without port).


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

Hostname without port
INPUT
URL: https://example.com:8080/page
OUTPUT
example.com
Full hostname with subdomain
INPUT
URL: https://www.subdomain.example.com/page
OUTPUT
www.subdomain.example.com

GTM Configuration

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

Read-only Preview
extractHostname
URL
💾 The URL to extract the hostname 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.


Under the Hood

📜 View Implementation Code
/**
 * Extracts the hostname from a given URL.
 *
 * @param {string} data.src - The URL to extract the hostname 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 hostname from the URL, or undefined if the input is invalid.
 *
 * @framework ggLowCodeGTMKit
 */

const parseUrl = require('parseUrl');

const extractHostname = function(url) {
    const parsed = parseUrl(url);
    return parsed && parsed.hostname || undefined;
};

const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);

// ===============================================================================
// extractHostname - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const value = applyCast(data.pre, data.src);
return out(extractHostname(value));

// ===============================================================================
// extractHostname() – Apply Mode
// ===============================================================================
/*
return function(value) {
   return out(extractHostname(value));
};
*/
🧪 View Test Scenarios (5 tests)
✅ '[example] Hostname without port'
✅ URL without port - should extract hostname
✅ '[example] Full hostname with subdomain'
✅ URL with query, hash and port - should extract hostname only
✅ Invalid URL - should return undefined