Placeholder
import { extractPlaceholders, replacePlaceholders, escapeRegExp } from '@bbc/front-end-kit/js/utils/placeholder';
// or via the default export:
import placeholder from '@bbc/front-end-kit/js/utils/placeholder';
Placeholder utils is a set of regex-based methods that help working with placeholders inside strings.
Tips
Can possibly be replaced by the template function of Lodash.
escapeRegExp(str)
Escapes any characters in a string that have special meaning in regular expressions. Used internally by extractPlaceholders and replacePlaceholders, but also useful standalone.
Parameters
str(string): The string to escape.
Returns
string — the escaped string.
extractPlaceholders(str, openSymbol, closeSymbol)
Extracts all placeholder names from a string.
Parameters
str(string): The string to extract placeholders from.openSymbol(string, default'{{'): The opening delimiter.closeSymbol(string, default'}}'): The closing delimiter.
Returns
string[] — an array of the placeholder names found (without the surrounding symbols).
import { extractPlaceholders } from '@bbc/front-end-kit/js/utils/placeholder';
const placeholders = extractPlaceholders('Hello, my name is {{ name }} and I\'m a {{ job }}.');
console.log(placeholders);
// ['name', 'job']
replacePlaceholders(str, values, openSymbol, closeSymbol)
Replaces placeholders in a string with their corresponding values from a dictionary object.
Parameters
str(string): The string containing placeholders.values(Object): A dictionary ofplaceholder: valuepairs.openSymbol(string, default'{{'): The opening delimiter.closeSymbol(string, default'}}'): The closing delimiter.
Returns
string — the string with placeholders replaced by their corresponding values. Unmatched placeholders are left as-is.
Known bug
The source checks value === 'function' (comparing the value to the string 'function') to detect function values. This condition can never be true for an actual function — the function-as-value branch is effectively dead code. Passing a function as a value will result in it being ignored and the placeholder left unreplaced.
import { replacePlaceholders } from '@bbc/front-end-kit/js/utils/placeholder';
const result = replacePlaceholders('Hello, my name is {{ name }} and I\'m a {{ job }}.', {
name: 'Nicolas',
job: 'Front-end ninja'
});
console.log(result);
// 'Hello, my name is Nicolas and I\'m a Front-end ninja.'
Default export
The file also exports a default object bundling all three functions:
import placeholder from '@bbc/front-end-kit/js/utils/placeholder';
placeholder.extractPlaceholders(str);
placeholder.replacePlaceholders(str, values);
placeholder.escapeRegExp(str);