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

130
Vistas
Complex string manipulation by JavaScript regexp

I am generating some meaningful name with the following rule in a JavaScript/Node JS program:

Input: "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId"

Expected output: "TenancyAccountAccountPublicIdWorkspaceWorkspacePublicIdRemove-userUserPublicId"

Rules:

  1. replace any character with zero or more underscore to the non-underscored uppercase Example:x | __*x => X
  2. If exists remove last _

This is what is tried so far, looking for better alternatives, if any:

const convertBetterString = (input) => {
    const finalString = [];
    if (input && input.includes('_')) {
        const inputStringSeparation = input.split('_');
        if (inputStringSeparation.length > 1) {
            if (inputStringSeparation[inputStringSeparation.length - 1] === '') {
                inputStringSeparation.splice(inputStringSeparation.length - 1, 1);
            }
            inputStringSeparation.forEach((val, index) => {
                if (val === '' && inputStringSeparation[index + 1]) {
                    const actualString = inputStringSeparation[index + 1];
                    const formattedString = actualString.charAt(0).toUpperCase() + actualString.slice(1);
                    finalString.push(formattedString);
                }
            });
            return finalString.length > 0 ? finalString.join('') : inputStringSeparation.join('');
        } else {
            return input.charAt(0).toUpperCase() + input.slice(1);
        }
    } else {
        return input;
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Split and slice

const capitalise = str => str.slice(0,1).toUpperCase() + str.slice(1); // you can add more tests

const str = "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId"
const newStr = str.split(/_+/)
  .map(word => capitalise(word))
  .join("")
console.log(newStr)

Regexp with optional chaining

const str = "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId_"

const newStr = str.replace(/(?:_+|^)(\w)?/g, (_,letter) => letter?.toUpperCase() ?? "")

console.log(newStr)

Explanation

(?:_+|^) non-capturing the underscore OR start
(\w)? followed by 0 or 1 letter to be captured
(_,letter) => letter?.toUpperCase() ?? "") ignore the match and uppercase the letter if found, that ignores trailing underscores too

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use

const str = "tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId__";
const newStr = str
    .replace(/(?:^|_)_*([^\s_])|_+$/g, (_, x) => x ? x.toUpperCase() : '')
console.log(newStr);

The /(?:^|_)_*([^\s_])|_+$/g regex matches all occurrences of

  • (?:^|_) - start of string or _
  • _* - zero or more underscores
  • ([^\s_]) - Group 1: any char other than whitespace and _.
  • | - or
  • _+$ - one or more _s at the end of string.

The (_, x) => x ? x.toUpperCase() : '' replacement remove all the underscores (even if they are at the end of string) and turns the Group 1 value (x) to upper case.

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