• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Draft / Join Strings with Commas and “And” in JavaScript

Join Strings with Commas and “And” in JavaScript

Last updated on July 16, 2020 by Sal Ferrarello

In English the rules we use for joining a list of items involves more work than a standard join in JavaScript.

Here is JavaScript code to join an array of elements with commas (,) and an and.

Code

/**
 * Join array of strings with commas (,) and "and".
 *
 * @example input ['one, 'two', 'three'];
 * @example return "one, two, and three"
 *
 * @param {string[]} array of strings.
 * @return {string} string created by joining the 
 *                  array with commas and "and".
 */
function addCommasAndAnd(list) {
  if (list.length < 3) { return list.join(' and '); }

  return `${list.slice(0, - 1).join(', ')}, and ${list[list.length - 1]}`;
};

Thank You

Thank you to Mike England for his help crafting this solution.

Future Solution

The browser native Intl.ListFormat will perform exactly this sort of joining with commas (,) and and however at the time of this writing browser support is limited.

If you want to plan for the future, you can use this functionality with a polyfill.

Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit
Warning! This is a draft, not a finalized post. See full draft disclosure.

Filed Under: Dev Tips, Draft, Programming, Solution Tagged With: JavaScript

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in