Search code examples
javascriptjsontemplate-literals

Using template literals in JSON (discord.js)


I have this JSON object:

"question": "The question, asked by ${users[index]}, was: \n\n${questions[index]}."

in a file called "config.json". In a separate file named "app.js", I have this line of code:

message.channel.send(config.question);

When the code runs, message.channel.send(config.question) outputs:

The question, asked by ${users[index]}, was:

${questions[index]}.

Is there any way to treat ${users[index]} and ${questions[index]} as template literals? Essentially I want the output to be something like this:

The question, asked by Steve, was:

Hello world!.

(assuming users[index] == "Steve" and questions[index] == "Hello World!")

I searched around for answers, but they all came to using additional Javascript or saying it's not possible. Why, then, if it's not possible, would this work?:

message.channel.send("The question, asked by ${users[index]}, was: \n\n${questions[index]}"); outputs:

The question, asked by Steve, was:

Hello world!.


Solution

  • To do string interpolation in JavaScript, you need to use backtick (`) for the string literal.

    For example:

    `The answer is ${myVar}!`
    

    will interpolate myVar into your string.