|
/* A little utility to execute strings as template literals */ |
|
|
|
|
|
|
|
// https://gist.github.com/naturecodevoid/2a6dc850e0005dbba3a04549a9779890#file-executetemplateliteral-js |
|
const executeTemplateLiteral = (string, args, argNames, replace$ = true) => { |
|
let temporary = `${string}`; |
|
if (replace$) temporary = temporary.replaceAll("{", "${"); |
|
return new Function(...argNames, `return \`${temporary}\`;`)(...args); |
|
}; |
|
|
|
|
|
|
|
/* And here's an es2015 version: */ |
|
|
|
|
|
|
|
// https://gist.github.com/naturecodevoid/2a6dc850e0005dbba3a04549a9779890#file-executetemplateliteral-js |
|
// Making a variable outside the strict mode block enables non-strict files to use this code |
|
var executeTemplateLiteral = null; |
|
// The rest was made by Babel |
|
{ |
|
"use strict"; |
|
|
|
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } |
|
|
|
executeTemplateLiteral = function executeTemplateLiteral(string, args, argNames) { |
|
var replace$ = arguments.length <= 3 || arguments[3] === undefined ? true : arguments[3]; |
|
|
|
var temporary = "" + string; |
|
if (replace$) temporary = temporary.replaceAll("{", "${"); |
|
return new (Function.prototype.bind.apply(Function, [null].concat(_toConsumableArray(argNames), ["return `" + temporary + "`;"])))().apply(undefined, _toConsumableArray(args)); |
|
}; |
|
} |
|
|
|
|
|
|
|
/* Example: */ |
|
|
|
|
|
|
|
const a = 1; |
|
console.log(executeTemplateLiteral("{a} test123", [a], ["a"])); |
|
// => 1 test123 |
|
|
|
// You can also: |
|
// - use normal template literals |
|
// - change the names of variables |
|
|
|
const b = 2; |
|
console.log(executeTemplateLiteral("${a} test123", [b], ["a"], false)); |
|
// => 2 test123 |