0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptの「タグ付きテンプレートリテラル」を初めて知った話

Last updated at Posted at 2025-05-24

タグ付きテンプレート

タグ付きテンプレートリテラルはテンプレートリテラルの拡張機能です。タグ付きテンプレートリテラルを学ぶ前に、まずはテンプレートリテラルについて見てみましょう。

テンプレートリテラル

テンプレートリテラルはES6に導入された文字列操作の機能です。JavaScript内でテンプレートリテラルを記述するには、バッククォート(`)を使います。
これを使うことで、複数行文字列、埋め込み式、文字列の操作など簡単に行えるようになります。
テンプレトリテラルの使いかた:

    const user = "アダム";
    const message1 = "ようこそ、" + user + ""; // これは普通の書き方です
    const message2 = `ようこそ、${user}様`; // これはテンプレトリテラルを使った例文です
    const message3 = `今日がいい天気ですね。
                    本を読むにはぴったりです。
                    `;// 複数行文字列を使ったテンプレトリテラル
    console.log(message1);
    console.log(message2);
    console.log(message3);

テンプレートリテラルは普段から使ってるんですが、今日は「タグ付きテンプレートリテラル」というものを初めて知りました。

タグ付きテンプレートリテラル

タグ付きテンプレートリテラルはテンプレートリテラルの拡張機能です。タグを使うことで、テンプレートリテラルを関数で処理することができます。タグ関数の第一引数は文字列の配列で、それ以外の引数全ては式の値です。これらの引数に対して任意の処理を行い、加工した文字列を返すことができます。
例文をみましょう:

    function person(strArr, username, today){
        let result = strArr[0] + username + strArr[1] + today;
        return result;
    }
    const username = `ジョーン`;
    const today = `土曜日`;
    console.log(person`ようこそ、${username}様。今日は${today}です。`);

上の例文を理解しましょう。「ようこそ」、「様」、「今日」、「です。」は第一引数の配列として渡され、変数username、todayは式の値として扱われます。
簡単に説明すると、person関数の引数は次のように解釈されます:

    strArr -> ["ようこそ", "", "今日", "です。"];
    username -> ${username}
    today -> ${today}

引数は何枚いるのかわからない場合は、こやって使えます:

    function person(strArr, ...values){// values -> [username, today]
        const result = values.reduce((accumulator, value, index) => {
        	return accumulator + value + strArr[index + 1];//strArr 配列は、常に values 配列より 一つ多く要素を持ちます。
        }, strArr[0]);
        return result;
    }

最後まで読んでいただきありがとうございます。ご質問やご指摘があれば、ぜひコメントで教えてください!

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?