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
- Regular Expression: The regex pattern /(^|. *)([a-z])/g matches:
- The start of the string (^)
- OR a period followed by optional spaces (. *)
- Followed by a lowercase letter ([a-z])
- The g flag makes it a global search (finding all matches)
-
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.
-
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.