user9895412
user9895412

Reputation:

How do I format names to capitalize the first character of every name/word separated by either spaces or hyphens?

There are lots of simple solutions out there to format the first character in every word by splitting a string (using split(' ')) but nothing explained how to handle real-world examples where people may have more than 1 word in their name, AND these words may be separated by spaces OR hyphens.

If you've found a more elegant solution, please share. I did my fair share of Googling but came up empty so I posted this.

Example Data

Ideally, I'd like to see solutions that don't involve regex, but feel free to add your regex answers if you think they're simpler.

Bonus Points

Bonus points if you can show how to handle names like DeSouza, FitzGerald, McDonald, MacIntyre, O'Henry, etc.

Upvotes: 0

Views: 113

Answers (3)

user9895412
user9895412

Reputation:

How's this?

const inputData = {
  firstName: 'First name',
  lastName: 'last-name',
}

function formatName(name) {
  let formattedName = name.split(' ')
  formattedName = formattedName.map((word) => {
    return word.charAt(0).toUpperCase() + word.slice(1)
  })
  formattedName = formattedName.join(' ')

  let hyphenIndexes = []
  for (let i = 0; i < formattedName.length; i++) {
    if (formattedName[i] === '-') {
      hyphenIndexes.push(i)
    }
  }
  for (let i = 0; i < hyphenIndexes.length; i++) {
    // capitalize the character after the hyphen
    formattedName =
      formattedName.slice(0, hyphenIndexes[i] + 1) +
      formattedName[hyphenIndexes[i] + 1].toUpperCase() +
      formattedName.slice(hyphenIndexes[i] + 2)
  }
  return formattedName
}

const fullName = formatName(inputData.firstName) + " " + formatName(inputData.lastName)

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Use map and in one iteration check for previous char is "-", " " or start and do uppercase conversion of that char.

const capSentence = (line) =>
  [...line]
    .map((char, idx, arr) =>
      [undefined, " ", "-"].includes(arr[idx - 1])
        ? char.toUpperCase()
        : char.toLowerCase()
    )
    .join("");

console.log(capSentence("Norm garcia"));
console.log(capSentence("stephen white-black"));

Upvotes: 0

lusc
lusc

Reputation: 1406

You could use a regular expression with \b to match the start of a word and \w to match the first character of said word. More about \b.

const names = [
    'Norm garcia',
    'stephen white-black',
    'lucy-lou ladyface',
    'billy joe davidson',
    'bobby savannah nick-nickerson',
];

for (let i = 0; i < names.length; ++i) {
    names[i] = names[i].toLowerCase().replace(/\b\w/g, m => m.toUpperCase());
}

console.log(names);

Upvotes: 1

Related Questions