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

269
Vistas
¿Cómo obtener etiquetas personalizadas en un texto y poner otro texto?

La pregunta del encabezado puede no ser fácil de entender. Espero que puedas entender mi información detallada a continuación.

Tengo datos de oraciones a continuación, que tienen algunas etiquetas, representadas por [tn]tag[/tn] :

 const sentence = `[t1]Sometimes[/t1] that's [t2]just the way[/t2] it has to be. Sure, there were [t3]probably[/t3] other options, but he didn't let them [t4]enter his mind[/t4]. It was done and that was that. It was just the way [t5]it[/t5] had to be.`

Y tengo partes de la oración.

 const parts = [ "Sometimes that's just the way", "it has to be", "Sure,", "there were probably other options,", "but he didn't let them enter his mind.", "It was done and that was that.", "It was just the way it had to be." ];

El objetivo es agregar etiquetas en cada parte usando la oración anterior.

 const expectedOutput = [ "[t1]Sometimes[/t1] that's [t2]just the way[/t2]", "it has to be", "Sure,", "there were [t3]probably[/t3] other options,", "but he didn't let them [t4]enter his mind[/t4].", "It was done and that was that.", "It was just the way [t5]it[/t5] had to be." ];

Lo que he intentado hasta ahora son los siguientes, pero aparentemente no tiene sentido, y no termino nada.

  1. haga una oración clonada y elimine todas las etiquetas. (código abajo)
  2. encontrar todas las partes de la oración.
  3. [el problema es que no se como poner de nuevo las etiquetas]

Quiero preguntar, ¿hay alguna posibilidad de lograrlo? y cómo. Gracias


 export const removeTags = (content) => { content = content.replace(/([t]|[\/t])/g, ''); return content.replace(/([t\d+]|[\/t\d+])/g, ''); };
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Para una respuesta regular: /\[t\d+\]([^[]*)\[\/t\d+\]/g coincidirá con todas las palabras, incluidas las etiquetas, y luego agrupará todas las palabras dentro de esas etiquetas.

 let regex = /\[t\d+\]([^[]*)\[\/t\d+\]/g; let matches = [], tags = []; var match = regex.exec(sentence); while (match != null) { tags.push(match[0]); matches.push(match[1]); match = regex.exec(sentence); }

ahora solo necesitamos reemplazar todas las matches con tags dentro de parts

 let lastSeen = 0; for (let i = 0; i < parts.length; i++) { for (let j = lastSeen; j < matches.length; j++) { if (parts[i].includes(matches[j])) { lastSeen++; parts[i] = parts[i].replaceAll(matches[j], tags[j]) } else if (j > lastSeen) { break; } } }

Aquí hay un enlace para ver la expresión regular: regex101

Y aquí hay un JSFiddle para ver todo JSFiddle

about 4 years ago · Juan Pablo Isaza Denunciar

0

Aquí también hice una versión alternativa, así que la descargaré a continuación. Sin anidamiento como en @thchp pero un poco más fácil de leer en mi opinión.

 const sentence = "[t1]Sometimes[/t1] that's [t2]just the way[/t2] it has to be. Sure, there" + "were [t3]probably[/t3] other options, but he didn't let them [t4]enter his mind[/t4]. It " + "was done and that was that. It was just the way [t5]it[/t5] had to be."; const parts = [ "Sometimes that's just the way", "it has to be", "Sure,", "there were probably other options,", "but he didn't let them enter his mind.", "It was done and that was that.", "It was just the way it had to be." ]; const getTokens = (text) => { const tokens = text.match(/\[t[0-9]+\]/gm); const result = []; tokens.forEach(tokenOpen => { const tokenClose = "[/" + tokenOpen.substring(1, tokenOpen.length); const tokenStart = text.indexOf(tokenOpen) + tokenOpen.length; const tokenEnd = text.indexOf(tokenClose); result.push({ tokenOpen, tokenClose, value: text.substr(tokenStart, tokenEnd - tokenStart) }); }); return result; } const applyTokens = (parts, tokens) => { return parts.map(part => { const match = tokens.filter(x => part.includes(x.value)); if(!match.length) return part; const {value, tokenOpen, tokenClose} = match[0]; const index = part.indexOf(value); const partPre = part.substr(0, index); const partPost = part.substr(index + value.length, part.length); return partPre + tokenOpen + part.substr(index, value.length) + tokenClose + partPost; }); } const output = applyTokens(parts, getTokens(sentence)); console.log(output);

Agrega etiquetas a todas las apariciones de algún valor en una parte, por lo que el primer "eso" en el segundo elemento de la matriz "partes" también se envuelve. Si no desea eso, elimine el token una vez usado en "applyTokens".

about 4 years ago · Juan Pablo Isaza Denunciar

0

Aquí hay una solución que asume que no hay etiquetas anidadas, que todas las etiquetas se abren y cierran en la pieza. Además, esto supone que todos los caracteres de la oración están en parts . Para esta última suposición, tuve que agregar el archivo . después tiene que estar en la segunda parte esperada. También tuve que eliminar los caracteres de nueva línea de la oración, pero creo que fue por copiar/pegar. Esta solución recorrerá todos los caracteres y almacenará dos búferes paralelos: uno con las etiquetas y otro sin ellas. Usaremos el segundo para comparar con las partes y usaremos el primero para generar la salida.

 const sentence = `[t1]Sometimes[/t1] that's [t2]just the way[/t2] it has to be. Sure, there were [t3]probably[/t3] other options, but he didn't let them [t4]enter his mind[/t4]. It was done and that was that. It was just the way [t5]it[/t5] had to be.` const parts = [ "Sometimes that's just the way", "it has to be.", "Sure,", "there were probably other options,", "but he didn't let them enter his mind.", "It was done and that was that.", "It was just the way it had to be." ]; let bufferWithoutTags = "" let bufferWithTags = "" const output = [] const buffers = [] let tagOpened = false for (let i = 0; i < sentence.length; ++i) { let c = sentence[i] bufferWithTags += c if ( c === '[') { if (tagOpened && sentence[i+1] === "/") { tagOpened = false } else { tagOpened = true } while (c != ']') { c = sentence[++i] bufferWithTags += c } } else { bufferWithoutTags += c; } if (!tagOpened) { for (const part of parts) { if (part === bufferWithoutTags.trim()) { output.push(bufferWithTags.trim()) bufferWithTags = bufferWithoutTags = "" } } } } 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