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

228
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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