i am using this api to get results for my app. What i need to do is instead of writing the country name, i will use a variable which will contain the country name. I need to pass it in the api url
var countryName = "south-africa"
const fetchAPI = ()=> {
return fetch("/$countryName")
.then((response) => response.json())
.then((result) => {
//console.log(result)
i am using this api https://api.covid19api./live/country/south-africa to get results for my app. What i need to do is instead of writing the country name, i will use a variable which will contain the country name. I need to pass it in the api url
var countryName = "south-africa"
const fetchAPI = ()=> {
return fetch("https://api.covid19api./live/country/$countryName")
.then((response) => response.json())
.then((result) => {
//console.log(result)
Share
Improve this question
asked May 24, 2020 at 18:16
Moeez AtlasMoeez Atlas
1162 silver badges12 bronze badges
3 Answers
Reset to default 3Solution
My bet would be to use the Javascript string format with magic quotes:
This would lead to
var countryName = "south-africa"
const fetchAPI = ()=> {
return fetch(`https://api.covid19api./live/country/${countryName}`)
.then((response) => response.json())
.then((result) => {
//console.log(result)
Reference
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Template_literals
You can use a template string to achieve that use backticks ` instead of quotes ".
var countryName = "south-africa"
const fetchAPI = ()=> {
return fetch(`https://api.covid19api./live/country/${countryName}`)
.then((response) => response.json())
.then((result) => {
//console.log(result)
How to use template strings in javascript.
var foo = 'Hello world'
// expected result "my variable foo = Hello world"
console.log(`my variable foo = ${foo}`)
I hope this helps.
You can consider using string literal.
var countryName = "south-africa"
const fetchAPI = ()=> {
return fetch(`https://api.covid19api./live/country/${countryName}`)
.then((response) => response.json())
.then((result) => {
}
Or String Concatenation:
var countryName = "south-africa"
const fetchAPI = ()=> {
return fetch("https://api.covid19api./live/country/" + countryName)
.then((response) => response.json())
.then((result) => {
}
Resource: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Template_literals