I have an array of objects with a set of certain words like entities. For example :
footnotes: [
{ sourceText: 'red'},
{ sourceText: 'green'},
{ sourceText: 'yellow'},
{ sourceText: 'purple'},
{ sourceText: 'gray'},
{ sourceText: 'blue'}
]
And I have some random sentences. For example: 'I drive a red car among green fields and look at the gray sky'
The goal is to mark words with asterisks according to the object of entities:
'I drive a red* car among green** fields and look at the gray*** sky'
I'm trying to do this in a loop with silce and Regexp but I can't concatenate the string correctly
How can this be done ?
Here is my code
footnotes = [{
sourceText: "red",
solve: false
},
{
sourceText: "green",
solve: false
},
{
sourceText: 'yellow',
solve: false
},
{
sourceText: "purple",
solve: false
},
{
sourceText: "grey",
solve: false
},
{
sourceText: "blue",
solve: false
}
]
starGenerate = function(count) {
let result = ''
for (let i = 0; i < count; i++) {
result += '*'
}
return result
},
let post = {
id: 21321,
data: {},
lead: 'I drive a red car among green fields and look at the gray sky'
}
post.check = function() {
let str, concat = ''
let self = this;
let starcounter = 0
for (let i = 0; i < self.entities.length; i++) {
let reg = new RegExp(`${self.entities[i].sourceText}`);
if (match = reg.exec(self.lead) && self.entities[i].solve === false) {
concat = self.lead.replace(reg, `${self.entities[i].sourceText + starGenerate(++starcounter)}`)
self.entities[i].solve = true
}
}
}
post.entities = footnotes