JSFiddle - React, Tailwind, and code Playground
by ktstowell
HTML
The expected inputs and outputs are below. You can assume that the example object’s top-level keys will always be a hexadecimal key of length 8 characters. If there is no matching object for a placeholder, you should insert the string '<nothing>'.
Example string:
This is a string with {{ ab49fd20.key_1 }}, including {{ 9822df87.another_key }} and also {{ ab49fd20.key_2 }}.
JavaScript
var map = {
'ab49fd20': {
key_1: 'some data'
},
'9822df87': {
another_key: 'big data',
yet_another_key: 'small data'
},
default: '<nothing>'
};
var string = 'This is a string with {{ ab49fd20.key_1 }}, including {{ 9822df87.another_key }} and also {{ ab49fd20.key_2 }}.';
var interpolated = interpolate(string);
console.log(interpolated)
/**
* Interpolates strings and matches content with keys
*/
function interpolate(str) {
str = str || '';
// Subsequent validation not needed as loop will never enter if '.' doesn't exist
(str.match(/\{\{[a-f0-9]*.*?\}\}/g) || []).forEach(function(match) {
var search = (match.match(/[a-f0-9]*\.+[^\}\s]*/g) || [])[0],
segments = search && search.split('.'),
text = (map && map[segments[0]] && map[segments[0]][segments[1]]) || map.default;
str = str.replace(match, text, 'g');
});
return str;
}