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

177
Vistas
Javascript can you merge multiple `.replace()` methods?

For the first time ever, I have the need to manipulate a string quite heavily in JS. After playing around I've noticed how out of hand it can get. I'm no JS pro and I'm guessing there's a cleaner way to achieve my desired output?

Question: Is editing the sample string x, like I have done necessary or is there a better solution?

My goal is to go from this: _postcode_pricing_manual_weekend_evening to this: Manual Weekend Evening:

const x = '_postcode_pricing_manual_weekend_evening'; // Original String
console.log("Original:", x);

var str = x.replace('_postcode_pricing_',''); // Strip prefix
console.log('1:',str);

var finalStr =  str.replace(/_/g, ' '); // strip Underscores
console.log('2:',finalStr);

// Add ':'
finalStr = finalStr += ':';

// Split into words array
const words = finalStr.split(" ");

// Loop array capitalise first letter of each word '[0]'
for (let i = 0; i < words.length; i++) {
    words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}

// Put array back together.
console.log("Final output:",words.join(" "));

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

0

If by "merge" you mean chain multiple replaces together, yes.

str = x.replace('_postcode_pricing_', '').replace(/_/g, ' ') + ':'

...is perfectly acceptable.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Yes, you can chain methods, so long as the previous method returns a type that implements the next method in a chain.

As for your process, you have some redundancy. You replace underscores with spaces, but then discard those spaces with your split() call. You could simply split on undercscores.

const x = '_postcode_pricing_manual_weekend_evening'; // Original String
console.log("Original:", x);

const words = x
  .replace('_postcode_pricing_','')                   // remove prefix
  .split("_")                                         // split into words
  .map(word => word[0].toUpperCase() + word.slice(1)) // capitalize
  .join(" ");                                         // rejoin
 
console.log(`${words}:`);                             // final literal adding ':'

Another option would be to use a regular expression in the second replace, passing a callback as the second argument to transform each matched character.

const x = '_postcode_pricing_manual_weekend_evening'; // Original String
console.log("Original:", x);

const parsedString = x
  .replace('_postcode_pricing','')
  .replace(/_(\w)/g, (_, firstChar, offset) => 
    (offset > 0 ? ' ' : '') + firstChar.toUpperCase());
    
console.log(`${parsedString}:`);

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