The dollar ($) does not work to interpolate a string in Javascript

Asked

Viewed 196 times

6

I’m using a code that uses the dollar sign ($) Javascript, only when using the cipher it gives error in the console and the code to fetch the data of an API ends up not working. What I need to do for Javascript to recognize the dollar and interpolate correctly?

async addRepository(event) {
       event.preventDefault();
       const repoTnput = this.inputEl.value;

       if (repoTnput.length === 0)
            return;
       
       const response = await api.get('/repos/${repoInput}');
       const { name, description, html_url, owner: { avatar_url } } = response.data;
       // ...
}

1 answer

9


What you’re looking for is called Template Strings.

Template strings is a literal string that allows embedded expressions.
This literal is delimited by serious accents ` instead of the traditional simple quotes ' or double quotes ".

The string template can also contain placeholders delimited by a dollar sign $ and keys {} around an expression that will be inserted in the string.

Example:

let a = 3;
let b = 4;

console.log(`a + b = ${a+b} e a * b = ${a*b}`);

In your code:

const response = await api.get(`/repos/${repoInput}`);
  • @hkotsubo, how did you get this magic?

  • 1

    Thus: https://meta.stackexchange.com/q/437/401803

Browser other questions tagged

You are not signed in. Login or sign up in order to post.