I'm working on a replacement process where I'm given a list of begin and end indicies saying I need to replace a word with tags. For instance, if I'm given the string below
"a lovely day at the office to meet such a lovely woman. I loved her so much"
I then see the list of indices below
[
{
beginOffset : 2,
endOffset : 8
},
{
beginOffset : 42,
endOffset : 48
},
{
beginOffset : 58,
endOffset : 63
}
]
Notice the word "lovely" isn't the only word I'm looking for. It's completely based on indexes. Below was my attempt but I'm running into so many problems trying to conceptualize what would make the most sense. I don't think regex would help me since its not a specific word. Anyone have experience doing something like this?
var indices = [{
beginOffset: 2,
endOffset: 8
},
{
beginOffset: 42,
endOffset: 48
},
{
beginOffset: 58,
endOffset: 63
}
];
var teststring = "a lovely day at the office to meet such a lovely woman. I loved her so much";
let lastindex = 0;
indices.forEach(element => {
var snippet = teststring.substr(lastindex, element["endOffset"])
teststring = teststring.substr(lastindex, element["beginOffset"]) + '<b>' + teststring.substr(element["endOffset"], element["beginOffset"])
// increment to account for the <b> brackets
lastindex = element["endOffset"] + 7 + 1;
});
console.log(teststring);
The resulting string needs to look like this dynamically:
"a <b>lovely</b> day at the office to meet such a <b>lovely</b> woman. I <b>loved</b> her so much"