Search⌘ K

Removing Those Weird Commas

Discover how to address the issue of unwanted commas in your JavaScript template literals when embedding array results. This lesson teaches you how to properly format strings by joining arrays without commas, improving your functional Wikipedia search UI using RamdaJS tools.

We'll cover the following...

If you stayed sharp last lesson, you noticed something off about our fresh UI.

widget

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?

Javascript (babel-node)
const joined = [1, 2, 3].toString();
console.log(joined);
// 1,2,3
console.log(typeof joined);
// string

Template literals do that if you put arrays inside of them.

Javascript (babel-node)
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!

Javascript (babel-node)
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

Javascript (babel-node)
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.

Javascript (babel-node)
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?

widget