I am using the Guardian API for a project to create a small News based web application to display content on a single page. I am mainly struggling with quoting in JavaScript when trying to write a function whithin a string. Based on the results the information should populate a card with the thumbnail, headline etc.
This is the script.
const GetNews = async (page) => {
console.log('Retrieving News Articles...')
var url = 'https://content.guardianapis.com/search?' +
' from-date=2023-01-01&' +
'to-date=2024-01-05&' +
'show-fields=trailText%2Cheadline%2Cthumbnail&' +
'page=' +page+
'&' +
'q=Sport&' +
'api-key=64b4ba41....';
var req = new Request(url);
let response = {"response":...}
console.log(response)
let str = ''
for (let item of response.results) {
str = str + '<div class="card my-4 mx-4" style="width: 20.5rem;">
<img src= '${item.thumbnail}' class="card-img-top" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">'${item.headline}'</h5>
<p class="card-text">'${item.trailText}'</p>
<a href="${item.webUrl}" target="_blank" class="btn btn-primary">Read More</a>
</div>
</div>'
}
I have tried different syntax but I don’t know if I am writing it incorrectly, it is to be noted that I am relatively inexperienced with JavaScript.
From following videos I have seen people write these expressions normally and they appear a different colour to signify they are seperate from the quotes, but after researching I have read the $ operator can only be used with single quotes hence why I wrote the code this way.
2
Answers
You are on the right track. In JS, you can execute expressions and put them in strings like so:
There is one mistake in your syntax. You are using single quotes (‘); you must use backticks (`) for strings using the "${}" syntax. Instead, use this:
These strings are called
Template Literals
. Learn more on this topic at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals.It might be easier and more secure to set your response items values directly to the DOM and not to a lengthy html string. But if you decide to stay with using a lengthy string, then I would make sure to use the String Template syntax from Mozilla’s MDN Web Docs for string interpolation.
Or you can manually update the DOM directly and avoid lengthy string concatenation.