JAVASCRIPT
Extract Placeholders (e.g., {{key}}) from Template Strings
Learn how to parse template strings using regular expressions to extract dynamic placeholders, like `{{variable_name}}`, for processing in web applications or UI rendering.
function extractPlaceholders(templateString) {
// Matches content inside double curly braces, e.g., {{key}}, {{ another_var }}
const regex = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
const matches = [...templateString.matchAll(regex)];
return matches.map(match => match[1]); // Returns the captured group (the key)
}
const template1 = "Hello, {{ name }}! Your order is {{ order_id }}.";
const placeholders1 = extractPlaceholders(template1); // ["name", "order_id"]
const template2 = "Welcome to our page.";
const placeholders2 = extractPlaceholders(template2); // []
const template3 = "Value is {{price_usd}} and quantity is {{ quantity }}.";
const placeholders3 = extractPlaceholders(template3); // ["price_usd", "quantity"]
How it works: The `extractPlaceholders` function uses the regex `\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g` to find patterns like `{{ key }}`. `\{\{` and `\}\}` match the literal curly braces. `\s*` matches optional whitespace. `([a-zA-Z0-9_]+)` is a capturing group that matches one or more alphanumeric characters or underscores, representing the placeholder key. The `g` flag ensures all matches are found. `matchAll()` returns an iterator of all matches, and we map over them to get only the captured group (the key itself), useful for identifying dynamic parts of a template.