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

235
Visualizações
format string to another string format javascript

I have the following function:

export const getFormatValue = (raw, value) => {
  let maskIndex = 0;
  let formattedValue = '';

  raw.split('').forEach(char => {
    if (value.length > maskIndex && value[maskIndex] === ' ') {
      formattedValue += ' ';
      maskIndex += 1;
    }
    formattedValue += char;
    maskIndex += 1;
  });

  return formattedValue;
};

It fails the following test cases

Expected: "A   BB   CCC"
Received: "A B BC C C"


> 11 |     expect(getFormatValue('ABBCCC', 'A   AA   AAA')).toBe('A   BB   CCC');

My code works for simple cases such as:

expect(getFormatValue('23', '0 0000 0000 0000')).toBe('2 3');

But soon as the "mask" pattern gets more complicated it fails.

The "mask" value is dynamic

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can reverse the string to be formatted, and then you can use the function Array.prototype.reduce and check the char in the pattern.

function getFormatValue(str, pattern) {
  const reversed = str.split("").reverse();
  return pattern.split("").reduce((a, c) => [...a, c === " " ? c : reversed.pop()], []).join("");
}

console.log(getFormatValue('ABBCCC', 'A   AA   AAA'));

about 4 years ago · Juan Pablo Isaza Relatório

0

One simple way of doing this:

export const getFormatValue = (raw, value) => {
   raw = raw.split('');
   return value.replace(/[^\s]/g, () => {
      return raw.shift() || '';
   });
}
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