Adding color dynamically to text within ion-card based on a regex pattern

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>&#64;{{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?

Answer №1

To make this function properly, we must utilize DomSanitizer along with the directive [innerHtml].

In your component TypeScript file:

// Component TypeScript File
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

export class YourComponent implements OnInit {
  items: any[] = [];

  constructor(
    private glyphService: GlyphService,
    private sanitizer: DomSanitizer
  ) {}

  ngOnInit(): void {
    this.glyphService.getAllGlyphs().subscribe(
      result => {
        this.items = result;
        // Sort by rune id to display newest first
        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_html = this.sanitizer.bypassSecurityTrustHtml(
            this.replaceKeywords(this.items[i].glyph_content)
          );
        }
        console.log(this.items);
      }
    );
  }

  replaceKeywords = (str: string): 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;
  }
}

In your HTML template:

<ion-card *ngFor="let item of items">
  <ion-card-header>
    <ion-card-title>&#64;{{item.username}}</ion-card-title>
    <ion-card-subtitle>{{item.glyph_date}}</ion-card-subtitle>
  </ion-card-header>
  <ion-card-content [innerHTML]="item.glyph_content_html">
  </ion-card-content>
</ion-card>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on incorporating an Ajax spinner to a Slideshow

I am in need of assistance with creating a manual slideshow that includes an ajax loader image. The goal is to display the loader image every time I click on the Previous or Next buttons, until the Test 1, Test 2, and Test 3 texts are fully loaded. Any sug ...

What is the best way to create a button that can cycle through various divs?

Suppose I want to create a scroll button that can navigate through multiple div elements. Here is an example code snippet: <div id="1"></div> <div id="2"></div> <div id="3"></div> <div id="4"></div> <div ...

How can I address the variations in CSS appearance between Firefox and Google Chrome?

I'm currently working on a table with two cells in each row just for fun. For the first row, I want both cells to display the same picture. To achieve this, I wrote the following CSS: tr:nth-child(1){ background-image:url("cat.jpg"); background-size: ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

Error in Webpack: JSX elements that are adjacent must be enclosed within a wrapper tag

After adding a new component and integrating it into my Main component, I encountered an error when running webpack. The error message displayed was: "Adjacent JSX elements must be wrapped in an enclosing tag" Below is the snippet of code where the iss ...

Input field with JQuery datepicker showing only months and years

I have encountered a question that closely resembles the one discussed here: year/month only datepicker inline The scenario I'm facing involves utilizing the input version instead of the div. In the case of using the div, the ui-datepicker-calendar ...

Issue encountered where Moment locale functionality is working in local development environment, but not functioning properly in the

My application built with Next.js requires displaying the date in Bengali instead of English. The issue arises after running the build command 'build:next build' where the production version displays the date in English (e.g. '20 January, Su ...

Error message: Please provide an expression with const in React JS component

Can you assist me with this issue? I am trying to determine if the user is registered. If they are registered, I want to display the home URL, and if they are not registered, I want to display the registration URL. To do this, I am checking the saved dat ...

Can routes be nested in React components?

I'm curious to know if there's a way to integrate nested routes in React, where the Navbar component serves as the parent for dashboard and properties. <Router> <Routes> <Route path='/' element={<Home />} /> ...

Inquiry from a newcomer: ASP.NET with jQuery

I am working on a webform with a file upload button that has some specific requirements. Whenever the file is uploaded using the button, I need the C# code behind to execute first before any jquery functions are called. <script> $(document.read ...

Enhancing CKEditor: Inserting new elements upon each dialog opening

I am facing a challenge where I need to dynamically add varying numbers of elements to a dialog window each time it is opened. Below is the code I am working with: CKEDITOR.on( 'dialogDefinition', function(ev) { var dialogName = ev.data.name ...

Elements are failing to respond to the padding and margin adjustments in my CSS styling

I've been experimenting with creating a visually appealing div that serves as the centerpiece of a website. Imagine it resembling a standard "news" link. The width set at 80%, an image aligned to the left with a border, a headline detailing the lates ...

"Please ensure that the field values in MessageEmbed are not left empty" stated discord.js

I've been working on a Discord bot using node.js, and I've encountered an issue with my kick and ban commands. I've tried to incorporate Discord embeds, but I keep running into this problem. Can anyone assist me with this? Here is the code ...

When outputting HTML, make sure to use an if statement

Looking to dynamically generate select options without using if statements. Instead of string manipulation, I want a cleaner solution. <select name="test"> <option disabled selected> -- Select an industry -- </option> <?php ...

retrieve the value of an HTML element once it has been modified

When I am working in a view, I encounter an issue where I need to retrieve the value of an HTML input box after it has been changed. Initially, the page loads with the following code: <input id="input_one" type="text" value = "apple" /> Upon loadin ...

unable to display the responseJson findings

I'm having trouble understanding why this function for an API on National Parks isn't working as expected. As a relatively new programmer, I find that seeking help from others can often shed light on issues I may have missed. Any assistance woul ...

I keep encountering the ExpressionChangedAfterItHasBeenCheckedError error in Angular, even though I'm calling it before the view is checked. What could

This is a piece of code that I have been working on home-component.ts export class HomeComponent implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked { loading = false; constructor() { } ngOn ...

Incorporating Copyleaks SDK into Angular: A Seamless Integration

Currently, I'm in the process of implementing the Copyleaks SDK with Angular to conduct plagiarism checks on two text area fields within an HTML form. Within the form, my goal is to incorporate two buttons: one to check for plagiarism on one text area ...

After setting up a Mongoose schema for authentication, how can I effectively perform database queries with MongoDB?

After successfully setting up authentication for my node.js (Express) app using Passport-local and Mongoose schema, I organized the folder structure as follows: app - app.js - config - auth.js - keys.js - passport.js - models - User.js - ...

The gridview fails to update when I attempt to click on the update button

Here is my updated code snippet for the GridView After clicking on the update button, the gridview is not being updated and instead reverting back to its previous value. However, the delete option is working correctly. Id = ( ...