Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda