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

204
Vistas
¿Cómo encontrar una cadena en la sintaxis y dividirlos en una matriz independientemente del orden?

Estoy tratando de dividir una cadena en partes separadas. Aquí como quiero

Tengo una cadena original

 let allString = 'This is the test to replace the string';

Convertiré la cadena original en una matriz de acuerdo con una matriz.

 let toReplace = [ { string: 'the test' }, { string: 'replace' }, ]

El resultado que quiero [ 'This is ', 'the test', ' to ', 'replace', ' the string' ] .

Ya tengo la respuesta para esto

 const processedText = toReplace .reduce( (result, { string }, index) => { const parts = result[result.length - 1].split(string); const [before, after] = parts; const newResult = result.slice(); const firstPass = index === 0; if (firstPass) { newResult.shift(); } else { newResult.pop(); } if (before) { newResult.push(before); } if (string) { newResult.push(string); } if (after) { newResult.push(after); } return newResult; }, [allString] )

El problema es que si cambio el orden de la matriz toReplace , ya no funcionará

 let toReplace = [ { string: 'replace' }, { string: 'the test' }, ]

Se saltará el segundo. Resultado [ 'This is the test to ', 'replace', ' the string', 'the test' ]

¿Cómo puedo solucionar este comportamiento?

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Puede pasar una expresión regular a split . El uso de grupos de captura mantendrá el separador en la matriz:

 let allString = 'This is the test to replace the string'; const processedText = allString.split(/(the test|replace)/); console.log(processedText);

El orden no es importante para esto:

 let allString = 'This is the test to replace the string'; const processedText = allString.split(/(replace|the test)/); console.log(processedText);

Puede construir dinámicamente la expresión regular:

 let toReplace = [{ string: 'the test' }, { string: 'replace' }]; const re = new RegExp(`(${toReplace.map(el => el.string).join('|')})`); let allString = 'This is the test to replace the string'; const processedText = allString.split(re); console.log(processedText);

about 4 years ago · Santiago Trujillo Denunciar

0

Puede recopilar los índices de los prases buscados y ordenar la matriz por índice y obtener la matriz dividida con ella.

 const text = 'This is the test to replace the string', toReplace = [{ string: 'replace' }, { string: 'the test' }], indices = [], result = []; for (const { string } of toReplace) { let i = text.indexOf(string); while (i !== -1) { indices.push([i, string]); i = text.indexOf(string, i + string.length); } } indices.sort(([a], [b]) => a - b); let i = 0, j = 0; if (indices[j]?.[0] === 0) { result.push(indices[j][1]); i += indices[j][1].length; j++; } while (i < text.length && j < indices.length) { result.push(text.slice(i, indices[j][0]), indices[j][1]); i = indices[j][0] + indices[j][1].length; j++; } if (text.slice(i)) result.push(text.slice(i)); console.log(result); console.log(indices);

about 4 years ago · Santiago Trujillo 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