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

229
Visualizações
Insert a character in a string based on character placement in another string

I have two strings:

const originalSegments = '[ABC][XYZ][123][789]';

const format = 'X-XX-X';

I need to create a new string where the dashes are inserted between sets of characters in originalSegments based on the placement of separators in format.

Each set of a characters between brackets is equal to one format character,

i.e. [*] === X

The desired end result is:

'[ABC]-[XYZ][123]-[789]'

I can get the length of each section in format:

const formatSections = format.split('-');
const formatSectionLengths = formatSections.map(section => section.length);
// => [1, 2, 1]

And the number of segments in originalSegments:

const originalSegmentsCount = (regexToString.match(/\]\[/g) || []).length + 1;
// => 4

But I'm not sure what to do next.

Would Array.prototype.reduce() work for this? Any advice is greatly appreciated!

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

0

Here is another approach:

const text='[ABC][XYZ][123][789]',
  pat='X-XX-X';

let txt=text.replaceAll("][","],[").split(",");
console.log(pat.split("").reduce((a,c)=>
 a + (c==="X"?txt.pop():c)
, ""))

about 4 years ago · Juan Pablo Isaza Relatório

0

I'd propose this solution for your case

const originalSegments = "[ABC][XYZ][123][789]";
//convert all segments to ["ABC","XYZ","123","789"]
const segments = originalSegments.split('[').filter(x => x).map(x => x.split(']')[0]);
const format = 'X-XX-X'
let result = []
let segmentIndex = 0
//loop through format to find X for the replacement
for(let i = 0; i < format.length; i++) {
  const character = format[i]
  //if the current character is X, replace with segment data
  if(character === "X") {
     result.push(`[${segments[segmentIndex]}]`)
     //check the next segment
     segmentIndex++
     continue
  }
  result.push(character)
}

//convert all results to a string
const finalResult = result.join("")

console.log(finalResult)

about 4 years ago · Juan Pablo Isaza Relatório

0

Interesting question. Another version using regex group matches and map

const originalSegments = '[ABC][XYZ][123][789]';
const format = 'X-XX-X';

const segs = originalSegments.match(/(\[[\w]+\])/g);
const output = [...format]
  .map((ch) => (ch === "X" ? segs.shift() : ch))
  .join("");
  
console.log(output)

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