Skip to content

pickParamsFromString — GTM Variable Template for String

VARIABLES › STRING
pickParamsFromString CORE String

Keeps only specified parameters from a query string or fragment, removing all others. Useful for preserving UTM parameters while stripping tracking IDs.


When to Use This

String Manipulation

Transform, clean, and normalize text data for consistent downstream processing.

URL Processing

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


Examples

Keep only UTM parameters
INPUT
Query String or Fragment: ?utm_source=google&fbclid=123&gclid=456&utm_medium=cpc
keys: ['utm_source', 'utm_medium']
Parameters to Keep: [{key: 'utm_source'}, {key: 'utm_medium'}]
Case insensitive matching: false
OUTPUT
?utm_source=google&utm_medium=cpc
Pick from hash fragment
INPUT
Query String or Fragment: #section=intro&debug=true&id=123
keys: ['section', 'id']
Parameters to Keep: [{key: 'section'}, {key: 'id'}]
Case insensitive matching: false
OUTPUT
#section=intro&id=123

GTM Configuration

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

pickParamsFromString
Query String or Fragment
💾 The query string or fragment to filter.

Supported formats:
  ✓ Query string: "?utm_source=google&fbclid=123"
  ✓ Fragment: "#section=intro&debug=true"
  ✓ Without prefix: "utm_source=google&fbclid=123"
Parameters to Keep
💾 List of parameter names to keep. All other parameters will be removed.

*** Keep only UTM parameters***

*** Pick from hash fragment***
⚙️ Enable to match parameter names regardless of case (e.g., "UTM_SOURCE" matches "utm_source").
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the input string before filtering.
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the result before returning it.
Query String or Fragment string
💡 Type any text to see the result update live
🎯 Using special value — click input to type instead
Test with:
Falsy
Truthy
Parameters to Keep list
pickParamsFromString()


Under the Hood

📜 View Implementation Code
/**
 * Filters a query string or fragment to keep only specified parameters.
 *
 * @param {string} data.src - A string starting with "?" or "#" to filter (e.g., "?a=1&b=2").
 * @param {Array} data.kys - Array of objects with parameter names to keep.
 * @param {boolean} [data.ci] - Optional flag to enable case-insensitive matching.
 * @param {Function|string} [data.out] - Optional output handler.
 *
 * Direct-mode specific parameters:
 * @param {Function} [data.pre] - Optional pre-processor function.
 * 
 * @returns {string} A filtered parameter string containing only the matching key-value pairs.
 *
 * @framework ggLowCodeGTMKit
 */
const decodeUriComponent = require('decodeUriComponent');
const encodeUriComponent = require('encodeUriComponent');
const getType = require('getType');

const createFlatArrayFromValues = function(list, property) {
    const result = [];
    if (!list) return result;
    for (let i = 0; i < list.length; i++) {
        const val = list[i][property];
        if (getType(val) === 'array') {
            for (let j = 0; j < val.length; j++) {
                result.push(val[j]);
            }
        } else if (val) {
            result.push(val);
        }
    }
    return result;
};

const pickParamsFromString = function(input, keys, caseInsensitive) {
    if (!input) {
        return '';
    }
    
    if (!keys || keys.length === 0) {
        return input.charAt(0) === '?' || input.charAt(0) === '#' ? input.charAt(0) : '';
    }
    
    const pickMap = {};
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        if (typeof key === 'string') {
            pickMap[caseInsensitive ? key.toLowerCase() : key] = true;
        }
    }
    
    const hasPrefix = input.charAt(0) === '?' || input.charAt(0) === '#';
    const prefix = hasPrefix ? input.charAt(0) : '';
    const raw = hasPrefix ? input.slice(1) : input;
    
    if (!raw) {
        return prefix;
    }
    
    const filteredPairs = [];
    const pairs = raw.split('&');
    
    for (let i = 0; i < pairs.length; i++) {
        const pair = pairs[i];
        if (!pair) continue;
        
        const eqIndex = pair.indexOf('=');
        const key = eqIndex >= 0 ? pair.slice(0, eqIndex) : pair;
        const lookupKey = caseInsensitive ? key.toLowerCase() : key;
        
        if (pickMap[lookupKey]) {
            if (eqIndex >= 0) {
                const value = pair.slice(eqIndex + 1);
                const decodedValue = decodeUriComponent(value);
                filteredPairs.push(key + '=' + encodeUriComponent(decodedValue));
            } else {
                filteredPairs.push(key);
            }
        }
    }
    
    const result = filteredPairs.join('&');
    return result ? (prefix + result) : prefix;
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// pickParamsFromString - Direct mode
🧪 View Test Scenarios (7 tests)
✅ Test pick single parameter
✅ '[example] Keep only UTM parameters'
✅ Test case insensitive matching
✅ '[example] Pick from hash fragment'
✅ Test empty input returns empty string
✅ Test no keys returns prefix only
✅ Test parameter not found returns prefix only