How to Extract Initials from a String in Angular

Introduction

In this article, we will learn how to extract initials from a  string. For example, if we give the word 'Artificial Intelligence', it will extract 'AI'.

Prerequisites

  • Basic Knowledge of Angular 2 or higher
  • Visual Studio Code
  • Node and NPM installed
  • Bootstrap(Optional)

Create an Angular Project

Create an Angular project by using the following command.

Now install Bootstrap by using the following command,

npm install bootstrap --save

Now open the styles.css file and add Bootstrap file reference. To add a reference in the styles.css file add this line.

@import '~bootstrap/dist/css/bootstrap.min.css';

Create Custom Pipe

Now, create a custom pipe by using the following command,

ng generate pipe Initials

Now open the Initials.pipe.ts file and add the following code.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'initials' })
export class InitialsPipe implements PipeTransform {
  transform(fullName: string): string {
    if (!fullName) return '';
    const nameParts = fullName.split(' ');
    return nameParts
      .map(part => part.charAt(0).toUpperCase())
      .join('');
  }
}

Now, create a new component by using the following command

ng g c actionmenu

Now open searchlist.actionmenu.html file and add the following code.

<div class="container" style="margin-top:10px;margin-bottom: 24px;">
<p>{{ 'Artificial Intelligence' | initials }}</p>
</div>

Now open app.component.html file and add the following code.

<div class="container" style="margin-top:10px;margin-bottom: 24px;">
  <div class="col-sm-12 btn btn-info">
    How to Extracts initials from a string in Angular
  </div>
</div>
<app-actionmenu></app-actionmenu>

Now run the application using npm start and check the result.

Extracts initials from a string in Angular

Summary

In this article, we learned how to extract initials from a  string.