Skip to content

Instantly share code, notes, and snippets.

@michelefenu
Last active November 25, 2021 15:08
Show Gist options
  • Save michelefenu/58cb949239ae62dc70bbe777d84b289b to your computer and use it in GitHub Desktop.
Save michelefenu/58cb949239ae62dc70bbe777d84b289b to your computer and use it in GitHub Desktop.
Angular Sentence Case pipe
import { Pipe, PipeTransform } from '@angular/core';
/**
* Pipe to convert a string to sentence case, meaning the first letter of each **sentence** is capitalized.
*
* @example
* {{ 'i am a string. and me too.' | sentenceCase }} => I am a string. And me too.
*
* @example
* {{ 'I AM A STRING. AND ME TOO.' | sentenceCase:true }} => I am a string. And me too.
*
* @param value The string to convert to sentence case.
* @param strict If true, will also convert other characters to lowercase. Use with caution, it will convert all non-alphanumeric characters to lowercase, including acronyms and proper names.
*
* @returns The string in sentence case.
*/
@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()}`
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment