文字列をテンプレート文字列に変換する 質問する

文字列をテンプレート文字列に変換する 質問する

テンプレート文字列を通常の文字列として作成することは可能ですか?

let a = "b:${b}";

そしてそれをテンプレート文字列に変換します。

let b = 10;
console.log(a.template()); // b:10

evalnew Functionおよび他の動的コード生成手段なしでは?

ベストアンサー1

私のプロジェクトでは、ES6 を使用して次のようなものを作成しました。

String.prototype.interpolate = function(params) {
  const names = Object.keys(params);
  const vals = Object.values(params);
  return new Function(...names, `return \`${this}\`;`)(...vals);
}

const template = 'Example text: ${text}';
const result = template.interpolate({
  text: 'Foo Boo'
});
console.log(result);

おすすめ記事