How to Remove Comma After Map Function in a String in JavaScript


Suppose we want to create an HTML string, something that might look like this:

const template = `
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
`

However, we want to populate the HTML string dynamically from an array.

const lst = [1, 2, 3];

The issue with template literals and maps

The natural tendency is to use template literals (i.e. the backticks) and to nest a map inside the template literal.

const template = `
  <ul>
    ${lst.map(t => (`<li>${t}</li>`))}
  </ul>
`

However, this results in commas after each element for some reason.

The commas show up because map() returns an array of strings, and the template literal will, by default, concatenate all the strings in this array using a comma.

Remove commas using join()

We can fix this by returning the full string instead of an array of strings.

We can do this easily by adding a .join('') after our map. This will concatenate all the strings in the array with an empty space.

const template = `
  <ul>
    ${lst.map(t => (`<li>${t}</li>`)).join('')}
  </ul>
`