UNPKG

@revenuecat/purchases-ui-js

Version:

Web components for Paywalls. Powered by RevenueCat

35 lines (34 loc) 1.41 kB
function capitalize(value) { return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase(); } const VARIABLE_MODIFIERS = { uppercase: (value) => String(value ?? "").toUpperCase(), lowercase: (value) => String(value ?? "").toLowerCase(), capitalize: (value) => { return String(value ?? "").replaceAll(/(\p{Letter}+)/giu, capitalize); }, }; // Only strips the leading "custom." prefix, preserving any "custom." within the key itself const CUSTOM_VARIABLE_PREFIX = /^\$?custom\./; function parseTemplate(template, variables) { // Match {{ product.variable | helper1 | helper2:arg1,arg2 }} patterns const templateRegex = /\{\{\s*([$a-z0-9._-]+)(?:\s*\|\s*([^}]*))?\s*\}\}/gi; return template.replace(templateRegex, (match, namePart, modifierPart) => { const variableName = namePart ?.trim() ?.replace(CUSTOM_VARIABLE_PREFIX, ""); const variable = variableName && variables[variableName]; if (variable === undefined) { return ""; } const modifierName = modifierPart?.trim(); if (modifierName === undefined) { return variable; } const modifier = VARIABLE_MODIFIERS[modifierName]; return modifier ? modifier(variable) : variable; }); } export function replaceVariables(input = "", variables) { return parseTemplate(input, variables ?? {}); }