Skip to content

Angular pipe to capitalize the first letter of each sentence

Published:  at 10:45 AM

Among Angular’s built-in pipes, there isn’t a direct way to capitalize the first letter of each sentence within a string.

For instance, we might want to transform this

hello i am a sentence. and so am i.

into this

Hello i am a sentence. And so am i.

Angular’s titlecase pipe comes close, but it capitalizes the first letter of every word, leading to a different result:

Hello I Am A Sentence. And So Am I.

Custom Solution: sentenceCase Pipe

Here’s a custom Angular pipe to achieve the desired sentence case transformation:

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

@Pipe({
  name: "sentenceCase",
})
export class SentenceCasePipe implements PipeTransform {
  transform(value: string = "", strict: boolean = false): string {
    if (strict) {
      value = value.toLowerCase();
    }

    return value.replace(
      /(^|\. *)([a-z])/g,
      (match, separator, char) => `${separator}${char.toUpperCase()}`
    );
  }
}

Explanation

  1. Regular Expression: The regex pattern /(^|. *)([a-z])/g matches:
  1. Replacement: The replacement function takes each match, extracts the separator (either start of string or period + spaces) and the lowercase letter. It then combines them, capitalizing the letter.

  2. Strict Mode (Optional): The strict parameter (defaulting to false) allows you to force the entire input to lowercase before applying the capitalization rules.

How to Use

<p>{{ 'hello i am a sentence. and so am i.' | sentenceCase }}</p>
<p>{{ 'HELLO I AM A SENTENCE. AND SO AM I.' | sentenceCase:true }}</p>

Output

Hello i am a sentence. And so am i.
Hello i am a sentence. And so am i.