Skip to content

replaceAllWithRegex — GTM Variable Template for String

VARIABLES › STRING
replaceAllWithRegex CORE String

Replaces all occurrences of a regular expression pattern in a string with a replacement value. Useful for pattern-based text transformations and data cleaning.


When to Use This

String Manipulation

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

Type Conversion

Safely convert between data types — strings, numbers, booleans, arrays, objects.

Filtering

Select or exclude items from collections based on criteria or predicates.

Formatting

Normalize casing, spacing, encoding, and presentation of data values.


Examples

Mask all numbers
INPUT
Input String: Order 123 and Order 456
Regular Expression Pattern: \\d+
Replacement Value: XXX
OUTPUT
Order XXX and Order XXX
Normalize whitespace
INPUT
Input String: hello world test
Regular Expression Pattern: \\s+
Replacement Value:
OUTPUT
hello world test

GTM Configuration

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

replaceAllWithRegex
Input String
💾 The input string where replacement will occur.

Supported formats:
  ✓ String
Regular Expression Pattern
🔍 The regular expression pattern to search for in the string. All occurrences will be replaced.

Supported formats:
  ✓ String (regex pattern)

⚠️ Escaping note: In this UI field, use single backslash (e.g., d+ for digits). GTM automatically handles the escaping.
Replacement Value
💾 The replacement value to use. Use empty string to remove matches.

Supported formats:
  ✓ String
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the input before replacement (e.g., normalize case, trim whitespace).
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the result string before returning it (e.g., str => str.trim(), str => str.toUpperCase()). Useful for chaining transformations on the output.
Input String 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
Replacement Value string
replaceAllWithRegex()


Under the Hood

📜 View Implementation Code
/**
 * Replaces all occurrences of a regular expression pattern in a string with a replacement value.
 * 
 * @param {string} data.src - The input string where replacement will occur.
 * @param {string} data.ptn - The regular expression pattern to search for in the string.
 * @param {string} data.rep - The replacement value to use.
 * @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 replacement.
 * 
 * @returns {string} The string with all occurrences of the regex pattern replaced.
 *
 * @framework ggLowCodeGTMKit
 */
const matchAll = function(stringToMatch, regexPattern) {
  const matches = [];
  let index = 0;
  while (index < stringToMatch.length) {
    const match = stringToMatch.substring(index).match(regexPattern);
    if (match) {
      matches.push(match[0]);
      index += match.index + match[0].length;
    } else {
      break;
    }
  }
  return matches.length > 0 ? matches : null;
};

const replaceAllWithRegex = function(input, pattern, replacement) {
    if (typeof input !== 'string' || typeof pattern !== 'string' || typeof replacement !== 'string') {
        return input;
    }
    
    const matches = matchAll(input, pattern);
    
    if (matches === null) {
        return input; // No matches found
    }
    
    let result = input;
  
    for (let i = 0; i < matches.length; i++) {
        result = result.replace(matches[i], replacement);
    }
    
    return result;
};

const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// replaceAllWithRegex - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const processedInput = applyCast(data.pre, data.src);
return out(replaceAllWithRegex(processedInput, data.ptn, data.rep));
// ===============================================================================
// replaceAllWithRegex(...) – Apply Mode
// ===============================================================================
/*
return function(input, pattern, replacement) {
   return out(replaceAllWithRegex(input, data.ptn, data.rep));
};
*/
🧪 View Test Scenarios (14 tests)
✅ Test with non-string input returns original value
✅ '[example] Mask all numbers'
✅ Test removing dollar signs
✅ '[example] Normalize whitespace'
✅ Test replacing word characters
✅ Test with no matches returns original string
✅ Test replacing special characters with escape sequences
✅ Test replacing emails with placeholder
✅ Test with non-string pattern returns original string
✅ Test with non-string replacement returns original string
✅ Test replacing line breaks
✅ Test case-insensitive pattern
✅ Test with null string returns original value
✅ Test with undefined string returns original value