Skip to content

matchAll — GTM Variable Template for String

VARIABLES › STRING
matchAll CORE String

Finds all matches of a pattern in a string and returns them as an array. Returns null if no matches are 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 all occurrences
INPUT
String To Search: hello world hello universe hello
Regular Expression Pattern: hello
OUTPUT
['hello', 'hello', 'hello']
Extract all numbers
INPUT
String To Search: abc123def456ghi789
Regular Expression Pattern: \\d+
OUTPUT
['123', '456', '789']
No matches returns null
INPUT
String To Search: hello world
Regular Expression Pattern: goodbye
OUTPUT
null

GTM Configuration

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

matchAll
String To Search
💾 The string to search within.

Supported formats:
  ✓ String
Regular Expression Pattern
🔍 The regular expression pattern to match in the string.

Supported formats:
  ✓ String (regex pattern)

⚠️ Escaping note: In this UI field, use single backslash (e.g., d+ for digits). GTM automatically handles the escaping.
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the string before matching (e.g., normalize case with str => str.toLowerCase(), remove extra spaces).
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the result array before returning it (e.g., arr => arr.length to count matches, arr => arr.join(',') to concatenate, arr => arr || [] to return empty array instead of null). Useful for chaining transformations on the output.
String To Search string
💡 Type any text to see the result update live
🎯 Using special value — click input to type instead
Test with:
Falsy
Truthy
Regular Expression Pattern string
matchAll()


Under the Hood

📜 View Implementation Code
/**
 * Simulates the behavior of String.prototype.match() with the g flag to find all matches.
 * 
 * @param {string} data.src - The string to search within.
 * @param {string} data.ptn - The regular expression pattern to match in the 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 matching.
 * 
 * @returns {Array|null} An array of all matches if found, or null if no matches are found.
 *
 * @framework ggLowCodeGTMKit
 */
const matchAll = function(stringToMatch, regexPattern) {
    const matches = [];
    let index = 0;
    
    // Keep matching until no more matches are found
    while (index < stringToMatch.length) {
        // Find the next match starting from the current index
        const match = stringToMatch.substring(index).match(regexPattern);
        
        // If a match is found, add it to the result and update the index
        if (match) {
            matches.push(match[0]); // match[0] is the full match
            index += match.index + match[0].length; // Move index to the end of the match
        } else {
            break;
        }
    }
    
    return matches.length > 0 ? matches : null;
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// matchAll - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const processedString = applyCast(data.pre, data.src);
return out(matchAll(processedString, data.ptn));
// ===============================================================================
// matchAll(...) – Apply Mode
// ===============================================================================
/*
return function(stringToMatch, regexPattern) {
   return out(matchAll(stringToMatch, data.ptn));
};
*/
🧪 View Test Scenarios (12 tests)
✅ '[example] Find all occurrences'
✅ '[example] Extract all numbers'
✅ Test with regex pattern for word characters
✅ Test with single match
✅ Test with overlapping pattern possibilities (greedy matching)
✅ Test with regex for email-like patterns
✅ Test with special characters in pattern
✅ Test with whitespace pattern
✅ Test with empty string returns null
✅ Test with undefined pattern returns null
✅ Test with invalid input returns null
✅ '[example] No matches returns null'