Removing Those Weird Commas
ES6 template strings join arrays with commas using the toString() method. We can fix that and improve our UI. (5 min. read)
We'll cover the following
If you stayed sharp last lesson, you noticed something off about our fresh UI.
It has extra commas! Why??
Template Literals
It’s all about how template literals join things. If you stick in an array, it’ll join it using the toString()
method.
See how this becomes joined?
const joined = [1, 2, 3].toString();console.log(joined);// 1,2,3console.log(typeof joined);// string
Template literals do that if you put arrays inside of them.
const nums = [1, 2, 3];const msg = `My favorite nums are ${nums}`;console.log(msg);// My favorite nums are 1,2,3
So by mapping our Wikipedia results inside of a template literal, we accidentally had commas inserted in between them!
export default ([query, names, summaries, links]) => `<h2>Searching for "${query}"</h2><ul class="list-group">${names.map((name, index) => `<li class="list-group-item"><a href=${links[index]} target="_blank"><h4>${name}</h4></a><p>${summaries[index]}</p></li>`)}</ul>`;
You can fix that by joining the array without commas. Just use an empty string!
Here’s with our [1, 2, 3]
example
const nums = [1, 2, 3];const msg = `My favorite nums are ${nums.join('')}`;console.log(msg);// My favorite nums are 123
No more commas! Let’s try that with our results map
.
export default ([query, names, summaries, links]) => `<h2>Searching for "${query}"</h2><ul class="list-group">${names.map((name, index) => `<li class="list-group-item"><a href=${links[index]} target="_blank"><h4>${name}</h4></a><p>${summaries[index]}</p></li>`).join('')}</ul>`;
Check out your UI. Looks much nicer right?