Skip to content

search β€” GTM Variable Template for String

VARIABLES β€Ί STRING
search CORE String
Direct (.tpl) Apply (.tpl)

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


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.


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

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



πŸ“œ 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