Search code examples
angularangular-pipe

Get the first word of a string in Angular using a Pipe?


I'm trying to write a pipe that prints the first word in a string. Following is my erroneous code that undesirably prints the first letter of a string.

For eg.

PIPE

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

@Pipe({
  name: 'firstWord'
})
export class GetFirstWord implements PipeTransform
{
    transform(value: string, args: any[]): string | boolean
    {
        if (value === null) {return false;}
        const firstWords = [];
        for (let i = 0; i < value.length; i++)
        {
          const words = value[i].split(' ');
          firstWords.push(words[0]);
        }
        return firstWords[0];
    }
}

COMPONENT

userName: string = 'Chuck Norris';

TEMPLATE

{{ userName | firstWord }}

OUTPUT

C

DESIRED OUTPUT

Chuck


Solution

  • You don't need a loop

    transform(value: string, args: any[]): string {
      if (!value) { return ''; }
      return value.split(' ')[0];
    }