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?
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);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);