Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

string - Apply tags to a text (angular)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...