JavaScript | テンプレートリテラル(Template Literal)を使って文字列を表す

javascrpit JavaScript
スポンサーリンク

初心者向け練習問題(+自動採点つき)

テーマ

「テンプレートリテラルの基礎:変数埋め込み・改行・式展開を理解しよう」

学べること

  • ${} の使い方(変数や式の展開)
  • 改行をそのまま扱う
  • 通常の文字列との違いを理解する

自動採点付き練習ページ

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>テンプレートリテラル練習クイズ</title>
<style>
body {
  font-family: "Segoe UI", sans-serif;
  margin: 2em;
  background: #fafafa;
}
pre {
  background: #f0f0f0;
  padding: 10px;
  border-radius: 8px;
}
input, textarea, button {
  font-size: 1em;
  margin-top: 8px;
}
button {
  padding: 6px 12px;
  cursor: pointer;
}
#result {
  margin-top: 16px;
  font-weight: bold;
}
.correct { color: green; }
.wrong { color: red; }
</style>
</head>
<body>
<h1>🎯 テンプレートリテラル練習(自動採点付き)</h1>

<h2>問題 1:</h2>
<p>次の変数を使って「こんにちは、たろうさん!」と出力してください。</p>
<pre>
const name = "たろう";
const message = /* ここを完成させよう! */
console.log(message);
</pre>
<textarea id="q1" rows="2" cols="60" placeholder="例: `こんにちは、${name}さん!`"></textarea>

<h2>問題 2:</h2>
<p>次の式をテンプレートリテラルで出力して、「2 + 3 = 5」と表示してください。</p>
<pre>
const a = 2, b = 3;
/* あなたのコード */
</pre>
<textarea id="q2" rows="2" cols="60" placeholder="例: console.log(`${a} + ${b} = ${a + b}`);"></textarea>

<h2>問題 3:</h2>
<p>テンプレートリテラルを使って次の詩をそのままの改行で出力してください。</p>
<pre>
さくら舞う  
春の空  
心おどる  
</pre>
<textarea id="q3" rows="4" cols="60" placeholder="ヒント: バッククォート(`)を使う"></textarea>

<br><button onclick="checkAnswers()">採点する</button>

<p id="result"></p>

<script>
function checkAnswers() {
  let score = 0;

  // 問1: こんにちは、たろうさん!
  try {
    const name = "たろう";
    const message = eval(document.getElementById("q1").value);
    if (message === "こんにちは、たろうさん!") score++;
  } catch {}

  // 問2: 2 + 3 = 5
  try {
    const a = 2, b = 3;
    const fn = new Function("a", "b", document.getElementById("q2").value + "; return undefined;");
    const consoleLog = console.log;
    let output = "";
    console.log = (msg) => { output += msg; };
    fn(a,b);
    console.log = consoleLog;
    if (output.trim() === "2 + 3 = 5") score++;
  } catch {}

  // 問3: 改行詩
  try {
    const userInput = document.getElementById("q3").value;
    const poem = eval(userInput);
    const correct = `さくら舞う
春の空
心おどる
`;
    if (poem === correct) score++;
  } catch {}

  const result = document.getElementById("result");
  result.innerHTML = `正答数:${score}/3`;
  result.className = score === 3 ? "correct" : "wrong";
  if (score === 3) {
    result.textContent += " 🎉 よくできました!";
  } else {
    result.textContent += " 😅 もう一度チャレンジ!";
  }
}
</script>
</body>
</html>
HTML

この教材のポイント

  • 即時フィードバック:採点ボタンで正解・不正解が即わかる
  • 安全な実行eval は限定的に使用し、入力値のみ評価
  • 改行問題でテンプレートの本領を体験できる

テンプレートリテラル中級編(自動採点つき練習)

ここでは、

  • 式展開の応用
  • ネストしたテンプレートリテラル
  • タグ付きテンプレート(Tagged Template)
    といった実践的な使い方を、クイズ形式で体験できます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>テンプレートリテラル中級クイズ(自動採点付き)</title>
<style>
body {
  font-family: "Segoe UI", sans-serif;
  margin: 2em;
  background: #f8f9fa;
}
h1 { color: #333; }
pre {
  background: #f0f0f0;
  padding: 10px;
  border-radius: 8px;
  white-space: pre-wrap;
}
textarea {
  width: 100%;
  font-size: 1em;
  margin: 5px 0 15px;
}
button {
  padding: 8px 16px;
  cursor: pointer;
  background: #0069d9;
  color: #fff;
  border: none;
  border-radius: 6px;
}
button:hover { background: #0053a4; }
#result {
  margin-top: 20px;
  font-weight: bold;
}
.correct { color: green; }
.wrong { color: red; }
</style>
</head>
<body>
<h1>⚙️ テンプレートリテラル 中級練習(自動採点付き)</h1>

<p>次の問題を完成させて、「採点する」を押すと結果が表示されます。</p>

---

<h2>問題 1:ネストしたテンプレート</h2>
<p>
次のコードで「こんにちは、はるさん!(今日の天気:晴れ)」を出力してください。
</p>
<pre>
const name = "はる";
const weather = "晴れ";
const msg = /* ここを完成させよう */
console.log(msg);
</pre>
<textarea id="q1" rows="2" placeholder="ヒント: `こんにちは、${name}さん!(今日の天気:${weather})`"></textarea>

---

<h2>問題 2:式展開の応用</h2>
<p>
次のコードで「税込価格: 110円」を出力してください(税率10%)。
</p>
<pre>
const price = 100;
const tax = 0.1;
const text = /* ここを完成させよう */
console.log(text);
</pre>
<textarea id="q2" rows="2" placeholder="例: `税込価格: ${price * (1 + tax)}円`"></textarea>

---

<h2>問題 3:タグ付きテンプレート</h2>
<p>
タグ関数 <code>highlight()</code> を使って、文字列内の変数を「★」で囲んで出力するようにしてください。  
結果は <code>お名前は ★はる★ です。</code> になります。
</p>
<pre>
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => 
    result + str + (values[i] ? "★" + values[i] + "★" : ""), "");
}

const name = "はる";
const output = /* ここを完成させよう */
console.log(output);
</pre>
<textarea id="q3" rows="2" placeholder="例: highlight`お名前は ${name} です。`"></textarea>

---

<button onclick="check()">採点する</button>

<p id="result"></p>

<script>
function check() {
  let score = 0;

  // 問1: ネスト
  try {
    const name = "はる";
    const weather = "晴れ";
    const msg = eval(document.getElementById("q1").value);
    if (msg === "こんにちは、はるさん!(今日の天気:晴れ)") score++;
  } catch {}

  // 問2: 式展開
  try {
    const price = 100, tax = 0.1;
    const text = eval(document.getElementById("q2").value);
    if (text === "税込価格: 110円") score++;
  } catch {}

  // 問3: タグ付きテンプレート
  try {
    function highlight(strings, ...values) {
      return strings.reduce((result, str, i) =>
        result + str + (values[i] ? "★" + values[i] + "★" : ""), "");
    }
    const name = "はる";
    const output = eval(document.getElementById("q3").value);
    if (output === "お名前は ★はる★ です。") score++;
  } catch {}

  const result = document.getElementById("result");
  result.innerHTML = `正答数:${score}/3`;
  result.className = score === 3 ? "correct" : "wrong";
  if (score === 3) {
    result.textContent += " 🎉 パーフェクト!中級クリアです!";
  } else {
    result.textContent += " 😅 惜しい!もう一度チャレンジしてみよう。";
  }
}
</script>
</body>
</html>
HTML

この中級版で学べること

機能解説
ネスト構文${} の中に他のテンプレートや式を入れる練習
計算式展開テンプレート中で四則演算を使う
タグ付きテンプレート${} の値を加工できるカスタム関数構文

テンプレートリテラル上級編(自動採点つき)

学べること

  • タグ付きテンプレートの本格活用
  • HTMLを安全に生成(XSS対策)
  • ${} 内の値をエスケープして扱う
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>テンプレートリテラル上級:安全HTML生成(自動採点付き)</title>
<style>
body {
  font-family: "Segoe UI", sans-serif;
  margin: 2em;
  background: #f9fafb;
}
pre {
  background: #f0f0f0;
  padding: 10px;
  border-radius: 8px;
}
textarea {
  width: 100%;
  font-size: 1em;
  margin: 5px 0 15px;
}
button {
  padding: 8px 16px;
  cursor: pointer;
  background: #0069d9;
  color: #fff;
  border: none;
  border-radius: 6px;
}
button:hover { background: #0053a4; }
#result {
  margin-top: 20px;
  font-weight: bold;
}
.correct { color: green; }
.wrong { color: red; }
#preview {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background: #fff;
}
</style>
</head>
<body>
<h1>🛡️ テンプレートリテラル上級:安全なHTML生成</h1>
<p>タグ付きテンプレート <code>safeHTML</code> を完成させて、ユーザー入力をエスケープしながらHTMLを生成してください。</p>

---

<h2>問題 1:</h2>
<p>次のコードで「<b>安全なHTML生成</b>」を出力するタグ付きテンプレート <code>safeHTML</code> を完成させてください。  
ヒント:危険な文字(<code>< > & ' "</code>)を置換して出力します。</p>

<pre>
function safeHTML(strings, ...values) {
  // ここを完成させよう!
}

const userInput = "<script>alert('XSS')</script>";
const output = safeHTML`<b>${userInput}</b>`;
console.log(output); // <b><script>alert('XSS')</script></b>
</pre>

<textarea id="q1" rows="6" placeholder="ヒント: values[i].replace(/[&<>'\"]/g, ...) を使う"></textarea>

---

<h2>問題 2:</h2>
<p>今度は <code>safeHTML</code> タグを使って、ユーザー名を安全にHTMLへ埋め込んでください。</p>
<pre>
const name = "<img src=x onerror=alert(1)>";
const html = /* ここを完成させよう */
document.getElementById("preview").innerHTML = html;
</pre>

<textarea id="q2" rows="3" placeholder="例: safeHTML`<p>ようこそ、${name}さん!</p>`"></textarea>

---

<button onclick="check()">採点する</button>

<p id="result"></p>
<div id="preview"></div>

<script>
function check() {
  let score = 0;

  // 問1
  try {
    eval(document.getElementById("q1").value);
    if (typeof safeHTML === "function") {
      const userInput = "<script>alert('XSS')</script>";
      const result = safeHTML`<b>${userInput}</b>`;
      if (result === "<b><script>alert('XSS')</script></b>") score++;
    }
  } catch {}

  // 問2
  try {
    const name = "<img src=x onerror=alert(1)>";
    eval(document.getElementById("q1").value); // safeHTML 定義を再利用
    const html = eval(document.getElementById("q2").value);
    if (html.includes("<img") && !html.includes("<img")) score++;
    document.getElementById("preview").innerHTML = html;
  } catch {}

  const result = document.getElementById("result");
  result.innerHTML = `正答数:${score}/2`;
  result.className = score === 2 ? "correct" : "wrong";
  if (score === 2) {
    result.textContent += " 🎉 完璧!安全なHTML生成をマスター!";
  } else {
    result.textContent += " 😅 惜しい!もう少し修正してみよう。";
  }
}
</script>
</body>
</html>
HTML

この上級版で得られるスキル

スキル説明
🧩 タグ付きテンプレート${} の値を加工・検証できる
🛡️ サニタイズ処理XSS対策としてHTMLエスケープを自動化
🧱 安全なinnerHTMLテンプレートを使って安全なDOM生成を実現
💬 実務応用ReactやLitなどのテンプレート処理理解の基礎
タイトルとURLをコピーしました