Telerik blogs
highlight_angular_header

Regular expressions are very powerful and I've been writing about them a lot lately. Particularly in how they can benefit you in Angular applications, whether that be for the web or mobile with NativeScript.

Back in 2015 I wrote a very popular tutorial called "Highlight Text in a String Using JavaScript and AngularJS," which is now worthy for an update. Things have changed between AngularJS and Angular, but the topic is still very valuable. Being able to manipulate HTML on the fly can solve many problems in Angular.

We're going to see how to highlight text within HTML using a query string and simple replace logic.

The logic behind what we're building is as follows:

  1. Use a regular expression to find a needle in a haystack;
  2. Replace any needles found with the same needle wrapped in an HTML tag with highlight CSS applied;
  3. Return the revised haystack for displaying on the screen;

In case this is your first time hearing about regular expressions, they are defined as the following via Wikipedia:

A sequence of characters that forms a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace”-like operations.

With this information we can start developing our project.

You can download a zip of the finished project here.

Creating the Angular Project for Text Manipulation

The content of this guide will be based around a project created with the Angular CLI. If you're not using the CLI, the information shouldn't be too difficult to grasp.

From the CLI, execute the following command:

ng new highlight-project

We'll be modifying HTML markup, TypeScript code, and CSS. First it makes sense to come up with some basic CSS for highlighting text.

Open the project's src/styles.css file and include the following:

.highlightText {
    background: yellow;
}

With the very simple CSS out of the way, we can have a look at the logic involved for manipulating the HTML. Open the project's src/app/app.component.ts file and include the following TypeScript code:

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {

    private content: string;
    public query: string;

    public constructor() {
        this.content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent a quam ornare, bibendum ligula a, rhoncus ligula. Etiam aliquet, justo sollicitudin imperdiet luctus, nulla justo sodales mi, sit amet semper nisl velit vel massa. In hac habitasse platea dictumst.";
    }

    public highlight() {
        if(!this.query) {
            return this.content;
        }
        return this.content.replace(new RegExp(this.query, "gi"), match => {
            return '<span class="highlightText">' + match + '</span>';
        });
    }

}

In the above code we have a private variable called content which contains our "haystack" data. We want it to be private because we don't want to render it to receive any of the manipulations directly.

In the highlight method, if the query (otherwise known as our "needle") is empty, just return whatever the haystack value is. If there is a query, we will use the replace function for strings. The cool thing about this function is that we can pass a regular expression as the search term and a function as the replace term.

The regular expression is going to be very simple, with it looking for all case insensitive occurrences of the query string. We're going to take the matches and wrap them in HTML tags with the CSS class name that we created.

Now open the project's src/app/app.component.html file so we can include the simple UI:

<h1> NGX Highlight Text Example</h1>
<div>
    <div>
        <input type="text" [(ngModel)]="query" placeholder="Query..." />
    </div>
    <p [innerHTML]="highlight()"></p>
</div>

The basic UI has a input field for the search criteria bound to the TypeScript query variable. The content displayed on the screen is powered by the p tag with the [innerHTML] attribute. The [innerHTML] attribute is very important as it allows us to render HTML from a variable. The data rendered comes from our highlight method.

Conclusion

You just saw how to do a few things with Angular. We saw how to render HTML on the screen via a variable and how to manipulate that HTML based on a query and regular expressions. This is all very useful information to have because it opens the door on what you can do with Angular.


nic-raboy
About the Author

Nic Raboy

Nic is a skilled application developer who has released several native and hybrid mobile applications to iTunes and Google Play. He writes about his development experiences related to making web and mobile app development easier to understand and has experience in Android, Node.js, Apache Cordova, Java, NoSQL, SQL, PHP, NativeScript and Unity3D.

Comments

Comments are disabled in preview mode.