I am trying to split an string into separate parts. Here how I want
I got an original string
let allString = 'This is the test to replace the string';
I will make the original string into array according to an array.
let toReplace = [
{
string: 'the test'
},
{
string: 'replace'
},
]
The result I want [ 'This is ', 'the test', ' to ', 'replace', ' the string' ].
I got the answer for this already
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]
)
The thing is if I change the order of the toReplace array, It won't work anymore
let toReplace = [
{
string: 'replace'
},
{
string: 'the test'
},
]
It will skip the 2nd one. Result [ 'This is the test to ', 'replace', ' the string', 'the test' ]
How can I fix this behavior?