aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--interpolate.js13
1 files changed, 13 insertions, 0 deletions
diff --git a/interpolate.js b/interpolate.js
index e69de29..36cf2f8 100644
--- a/interpolate.js
+++ b/interpolate.js
@@ -0,0 +1,13 @@
+const regex = /\${[^{]+}/g;
+
+export default function interpolate(template, variables, fallback) {
+ return template.replace(regex, (match) => {
+ const path = match.slice(2, -1).trim();
+ return getObjPath(path, variables, fallback);
+ });
+}
+
+//get the specified property or nested property of an object
+function getObjPath(path, obj, fallback = '') {
+ return path.split('.').reduce((res, key) => res[key] || fallback, obj);
+} \ No newline at end of file