Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
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

  • Norm garcia -> Norm Garcia
  • stephen white-black -> Stephen White-Black
  • Lucy-lou ladyface -> Loucy-Lou Ladyface
  • Billy joe davidson -> Billy Joe Davidson
  • bobby savannah nick-nickerson -> Bobby Savannah Nick-Nickerson

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.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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);

about 4 years ago · Juan Pablo Isaza Denunciar

0

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)
about 4 years ago · Juan Pablo Isaza Denunciar

0

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"));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda