Skip to content

search — GTM Variable Template for String

VARIABLES › STRING
search CORE String

Searches for a regular expression pattern in a string and returns the index of the first match. Returns -1 if no match is found.


When to Use This

String Manipulation

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

Extraction

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

Comparison

Test equality, containment, and ordering between values.

Regex

Pattern matching, extraction, and replacement using regular expressions.


Examples

Find digit position
INPUT
String to Search: Hello World
Regular Expression Pattern: World
OUTPUT
6
No match returns -1
INPUT
String to Search: Hello World
Regular Expression Pattern: xyz
OUTPUT
-1

GTM Configuration

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



Under the Hood

📜 View Implementation Code
/**
 * Simulates the behavior of String.prototype.search() using a regular expression literal.
 *
 * @param {string} data.src - The string to search within.
 * @param {string} data.rgx - The regular expression pattern as a string.
 * @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 searching.
 * 
 * @returns {number} Returns the index of the first match, or -1 if no match is found.
 *
 * @framework ggLowCodeGTMKit
 */
const search = function(searchData, regexPattern) {
    if (typeof searchData !== 'string' || typeof regexPattern !== 'string') {
        return -1;
    }
    return searchData.search(regexPattern);
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// search - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const value = applyCast(data.pre, data.src);
return out(search(value, data.rgx));
// ===============================================================================
// search(...) – Apply Mode
// ===============================================================================
/*
return function(searchData, regexPattern) {
   return out(search(searchData, data.rgx));
};
*/
🧪 View Test Scenarios (5 tests)
✅ '[example] Find digit position'
✅ String with pattern at beginning - returns 0
✅ '[example] No match returns -1'
✅ String with regex pattern - finds match using regex
✅ Non-string input - returns -1