I need to apply some tags (<b>, <i>,...) to some words in a string.
For now, I've done the following :
applyTaggings(text: string, posArray: any[], tag: any[]){
let first = '';
let sentence = '';
for(let i = 0; i < posArray.length; i++){
let beg = JSON.parse(posArray[i].tagging).begPos;
let end = JSON.parse(posArray[i].tagging).endPos;
if(i==0){
first = text.slice(0, beg)
let next = tag[0] + text.slice(beg, end) + tag[1];
sentence = first.concat('', next)
}
else{
let lastEnd = JSON.parse(posArray[i - 1].tagging).endPos;
let inBetween = text.slice(lastEnd, beg);
sentence = sentence.concat('', inBetween);
let next = tag[0] + text.slice(beg, end) + tag[1];
sentence = sentence.concat('', next);
if(i == posArray.length - 1){
let last = text.slice(end);
sentence = sentence.concat('', last);
}
}
}
return sentence;
}
Where posArray parameter is an array like this one :
posArray= [{
"id": 2605,
"tagging": "{"id":132,"begPos":4,"endPos":13}",
"review_status": null
},
{
"id": 2606,
"tagging": "{"id":135,"begPos":17,"endPos":22}",
"review_status": null
},
{
"id": 2606,
"tagging": "{"id":135,"begPos":60,"endPos":74}",
"review_status": null
}
]
And tag is just the specification of the tag, here bold :
tag = [`<b>`, `</b>`];
Then I call the function applyTaggings which matches to a variable and in the template I use [innerHTML]="variable" in the div I want the tagged text to appear.
It seems to work but I'm sure there are better and more efficient ways to do this.
How would you do it ? What are your thoughts on this ?
Thanks in advance!
question from:
https://stackoverflow.com/questions/65899933/apply-tags-to-a-text-angular 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…