JAVASCRIPT
Extracting Content Within Double Curly Braces
Learn to extract all dynamic content enclosed within double curly braces (e.g., `{{variable}}`) from a string using a JavaScript regex pattern.
const templateString = "Hello {{name}}! Your score is {{score}}.";
const variablesWithBraces = templateString.match(/\{\{([^}]+)\}\}?/g);
console.log(variablesWithBraces); // Output: ["{{name}}", "{{score}}"]
// To get just the variable names without braces:
const variableNames = templateString.match(/\{\{([^}]+)\}\}?/g)?.map(match => match.slice(2, -2));
console.log(variableNames); // Output: ["name", "score"]
How it works: The regex `/\{\{([^}]+)\}\}?/g` captures text between `{{` and `}}`. `\{\{` and `\}\}?` match the literal curly braces (escaped with `\`). The `([^}]+)` part is a capturing group that matches one or more characters that are not a closing curly brace (`}`). The `g` flag ensures all matches are found. The second part demonstrates how to further process the results to extract only the content within the braces.