Skip to content

Instantly share code, notes, and snippets.

@gecugamo
Created October 24, 2024 00:07
Show Gist options
  • Save gecugamo/361a45eb60ff1dd9b7373ca0122687b3 to your computer and use it in GitHub Desktop.
Save gecugamo/361a45eb60ff1dd9b7373ca0122687b3 to your computer and use it in GitHub Desktop.
function transformTemplatedString(template, replacements) {
return Object.entries(replacements).reduce((transformedString, [key, value]) => {
if (!/^[a-z|_]+$/i.test(key)) {
throw new Error('keys may only consist of letters and underscores');
}
const keyPattern = new RegExp(`%{${key}}`, 'g');
return transformedString.replace(keyPattern, value);
}, template);
}
transformTemplatedString(
'Cannot have insurance score less than %{minimum_insurance_score} and insurance lapse of %{minimum_days_for_lapse} or more days',
{minimum_insurance_score: '100', minimum_days_for_lapse: 5, foo: 'bar'}
)
// 'Cannot have insurance score less than 100 and insurance lapse of 5 or more days'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment