interpolate.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * @fileoverview Interpolate keys from an object into a string with {{ }} markers.
  3. * @author Jed Fox
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Public Interface
  8. //------------------------------------------------------------------------------
  9. /**
  10. * Returns a global expression matching placeholders in messages.
  11. * @returns {RegExp} Global regular expression matching placeholders
  12. */
  13. function getPlaceholderMatcher() {
  14. return /\{\{([^{}]+?)\}\}/gu;
  15. }
  16. /**
  17. * Replaces {{ placeholders }} in the message with the provided data.
  18. * Does not replace placeholders not available in the data.
  19. * @param {string} text Original message with potential placeholders
  20. * @param {Record<string, string>} data Map of placeholder name to its value
  21. * @returns {string} Message with replaced placeholders
  22. */
  23. function interpolate(text, data) {
  24. if (!data) {
  25. return text;
  26. }
  27. const matcher = getPlaceholderMatcher();
  28. // Substitution content for any {{ }} markers.
  29. return text.replace(matcher, (fullMatch, termWithWhitespace) => {
  30. const term = termWithWhitespace.trim();
  31. if (term in data) {
  32. return data[term];
  33. }
  34. // Preserve old behavior: If parameter name not provided, don't replace it.
  35. return fullMatch;
  36. });
  37. }
  38. module.exports = {
  39. getPlaceholderMatcher,
  40. interpolate
  41. };