Adding html tags to text

So in my app I have a page that displays a bunch of posts from Twitter. I want to apply a CSS class to the hashtags in these posts so that they’re highlighted in a different color from the text. For that, I wrote a simple function:

highlightHashtags(text) {
  let words = text.split(" ");
  for(let i in words) {
    if(words[i].substring(0,1) == "#") {
      words[i] = "<span class='hashtag'>" + words[i] + "<span>";
    }
  }
  return words.join(" ");
}

And I call that in the function where I get the tweet data from my server:

  // ...
  let text = tweets.statuses[i].full_text;
  t["text"] = this.highlightHashtags(text);
  // ...

(t is later pushed to the array tweets which is then used in the HTML as *ngFor="let tweet of tweets" - for clarity lol)

But when I try to print the text in the app’s page, it doesn’t apply the span tags but rather prints them as plain text.

Calling the function like {{ this.highlightHashtags(tweet.text) }} gives the same result.

I get that this is probably a security measure - but is there another way to do this?

Try…

<div [innerHTML]="this.highlightHashtags(tweet.text)"></div>

Amazing. So simple, thank you so much :smile:

1 Like

You could also rewrite you function a bit if you want to simplify it. :slight_smile:

hightlightHashtags(text) {
  return text.split(" ")
   .map(word => word[0] === "#" ? `<span class='hashtag'>${word}</span>` : word)
   .join(" ");
}

Also, this is the perfect thing to toss in a directive :slight_smile:

<div tweetHighlight *ngFor="let tweet of tweets">{{ tweet }}</div>

Edit: Previous version suggested pipe instead of directive, which was incorrect since this is dom manipulation