Last active
November 25, 2021 15:08
-
-
Save michelefenu/58cb949239ae62dc70bbe777d84b289b to your computer and use it in GitHub Desktop.
Angular Sentence Case pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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