Skip to content

getLength — GTM Variable Template for Value

VARIABLES › VALUE
getLength EXTENDED Value

Returns the length of a string or array.



Examples

String length
INPUT
Value To Measure: hello world
OUTPUT
11
Array length
INPUT
Value To Measure: [1, 2, 3, 4, 5]
OUTPUT
5

GTM Configuration

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

getLength
Value To Measure
💾 The value whose length is to be determined.

Supported formats:
  ✓ String
  ✓ Array
  ✓ Any (returns 0)
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the input before internal logic (e.g., convert object to string, normalize case). Internal transformations such as case handling will still apply afterward.
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the result before returning it (e.g., str => str + ' €', val => val !== undefined for boolean conversion). Useful for chaining transformations on the output.
Value To Measure array
💡 Type any text to see the result update live
🎯 Using special value — click input to type instead
Test with:
Falsy
Truthy
getLength()


Under the Hood

📜 View Implementation Code
/**
* Returns the length of a value, handling different types.
* 
* @param {any} data.src - The value whose length is to be determined.
* @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 getting length.
* 
* @returns {number} The length of the value if it's a string or array, 0 otherwise.
*
* @framework ggLowCodeGTMKit
*/
const getType = require('getType');
const getLength = function(value) {
   if (typeof value === 'string') { return value.length; }
   if (getType(value) === 'array') { return value.length; }
   return 0;
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// getLength - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const value = applyCast(data.pre, data.src);
return out(getLength(value));
// ===============================================================================
// getLength() – Apply Mode
// ===============================================================================
/*
return function(value) {
  return out(getLength(value));
};
*/
🧪 View Test Scenarios (7 tests)
✅ '[example] String length'
✅ Empty string - should return 0
✅ '[example] Array length'
✅ Empty array - should return 0
✅ Array with mixed types - should return array length
✅ Number input - should return 0
✅ Object returns 0