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

200
Visualizações
¿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 Respostas
Responde à pergunta

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 Relatório

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