My goal is to enhance the appearance of certain text elements by wrapping them in a span tag whenever a # or a @ symbol is detected, creating the look of usernames and hashtags on Twitter. Below is the code I am currently using:
TS FILE:
ngOnInit(): void {
this.glyphService.getAllGlyphs().subscribe(
result => {
this.items = result;
// sort by rune id so list is newest to oldest
this.items.sort((a, b) => Number(b.rune) - Number(a.rune));
for (let i = 0; i < this.items.length; i++) {
this.items[i].glyph_content = this.replaceIt(this.items[i].glyph_content);
console.log(this.items[i])
}
console.log(this.items)
}
);
}
replaceIt = (str: string) => {
const regex = /\B([\#\@][a-zA-Z]+\b)(?!;)/g;
const subst = `<span style="color:blue">$1</span>`;
const result = str.replace(regex, subst);
return result;
}
HTML FILE:
<ion-card *ngFor="let item of items" >
<ion-card-header>
<ion-card-title>@{{item.username}}</ion-card-title>
<ion-card-subtitle>{{item.glyph_date}}</ion-card-subtitle>
</ion-card-header>
<ion-card-content>
{{item.glyph_content}}
</ion-card-content>
</ion-card>
While I have successfully implemented the functionality to format the text as intended, it is displaying as plain text rather than actual HTML tags, resulting in an output like this:
test <span style="color:blue">@hey</span> <span style="color:blue">@uh</span> wow <span style="color:blue">#ah</span> words <span style="color:blue">#oh</span>
Is there a way to modify my code to dynamically wrap the target text within real span elements as I intend? Could leveraging *ngIf offer a creative solution in this context?