Tengo dos cadenas:
const originalSegments = '[ABC][XYZ][123][789]'; const format = 'X-XX-X'; Necesito crear una nueva cadena donde los guiones se inserten entre conjuntos de caracteres en originalSegments según la ubicación de los separadores en format .
Cada conjunto de caracteres entre corchetes es igual a un carácter de format ,
es decir [*] === X
El resultado final deseado es:
'[ABC]-[XYZ][123]-[789]' Puedo obtener la longitud de cada sección en format :
const formatSections = format.split('-'); const formatSectionLengths = formatSections.map(section => section.length); // => [1, 2, 1] Y el número de segmentos en originalSegments :
const originalSegmentsCount = (regexToString.match(/\]\[/g) || []).length + 1; // => 4Pero no estoy seguro de qué hacer a continuación.
¿ Array.prototype.reduce() para esto? ¡Cualquier consejo es muy apreciado!
Aquí hay otro enfoque:
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) , ""))Yo propondría esta solución para su caso
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)Interesante pregunta. Otra versión que usa coincidencias de grupos de regex y 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)