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

136
Vistas
Camel case to Title case doesnt work for the first letter

I need to make the given string to title case, no matter whether the input is lower or upper case

memberships 1 - contactGroupMembership - contactGroupId should return Memberships 1 - Contact Group Membership - Contact Group Id

memberships1-contactGroupMembership-contactGroupId should return Memberships 1 - Contact Group Membership - Contact Group Id

I have tried with

str.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1");
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You may use this 2 step solution for your case:

input = ['memberships 1 - contactGroupMembership - contactGroupId', 'memberships1-contactGroupMembership-contactGroupId'];

const re1 = /\B(?:[A-Z]|\d)|\b-\b|(?<=-)[a-z]/g;
const re2 = /\b[a-z]/g;

var repl = [];
input.forEach(str => {
  repl.push(str
    .replace(re1, ' $&')
    .replace(re2, m => m.toUpperCase())
  );
});

console.log(repl);

Explanation:

  • In the first .replace we insert space at desired places using first regex:

    \B(?:[A-Z]|\d)|\b-\b|(?<=-)[a-z]
    

This matches a non-word boundary followed by upper case letter or digit or a - that is surrounded with word boundaries on both sides or a lower case letter that must be preceded with a -. RegEx Demo 1

  • In the second step we match lower case letter after a word boundary and make it upper case.
about 4 years ago · Juan Pablo Isaza Denunciar

0

Very specific to this user case, but you can also use a replacer function to uppercase either the first character of a word or the first capital: str.replace(/(\b[a-z])|([A-Z]+)/g, (m,p1,p2)=> (p1 ? '' : ' ') + (p1 || p2).toUpperCase());

working: either beginning of the word (used in p1) or the first capital (p2) is found. The replacer function uppercases that match, and adds the extra space only if it is not a p1 match

Demo:

let str = 'memberships 1 - contactGroupMembership - contactGroupId';

str = str.replace(/(\b[a-z])|([A-Z]+)/g, (m,p1,p2)=> (p1 ? '' : ' ') + (p1  || p2).toUpperCase());

console.log(str);

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