DEV Community

Discussion on: Daily Challenge #190 - capitalizeFirstLast

Collapse
 
nombrekeff profile image
Keff

Cool, many ways of doing this.

This is what I came up with:

function capitalizeFirstLast(string = "") {
  const _firstLastWord = word => {
    if (!word || word.length <= 1) {
      return word.toUpperCase();
    }

    let len = word.length;
    const upperAt = i => word.charAt(i).toUpperCase();
    return `${upperAt(0)}${word.substr(1, len - 2)}${upperAt(len - 1)}`;
  };

  return string.length
    ? string
        .toLowerCase()
        .split(" ")
        .map(_firstLastWord)
        .join(" ")
    : string;
}