JSFiddle - React, Tailwind, and code Playground

by Jesper02

JavaScript

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

var 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 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);
}

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

console.log("parts", parts);