JSFiddle - React, Tailwind, and code Playground

by mckabue

JavaScript

function stringTemplate (html, data, options) {
            var _options = Object.assign({
                    interpolate: /\%\{(.+?)\}/g, //{{ }} => /\{\{(.+?)\}\}/g   %{ } => /\%\{(.+?)\}/g,
                    reExp: /(^( )?(var|if|for|else|switch|case|break|{|}|;))(.*)?/g
                }, options),
                code = 'with(obj) { var r=[];\n',
                cursor = 0,
                result,
                match;
            var add = function (line, js) {
                js ? (code += line.match(_options.reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
                    (code += line !== '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
                return add;
            };
            while (match = _options.interpolate.exec(html)) {
                add(html.slice(cursor, match.index))(match[1], true);
                cursor = match.index + match[0].length;
            }
            add(html.substr(cursor, html.length - cursor));
            code = (code + 'return r.join(""); }').replace(/[\r\t\n]/g, ' ');
            try {
                result = new Function('obj', code).apply(data, [data]);
            } catch (err) {
                console.error("'" + err.message + "'", " in \n\nCode:\n", code, "\n");
            }
            return result;
        }
        
        console.log(stringTemplate('/api/search?query=%{query}&page=%{page}', {
                        query: 'searchQuery',
                        page: 'page'
                    }))