Created
October 19, 2017 04:00
-
-
Save krabello/56a836517a46218ca1e4dbe1603dc081 to your computer and use it in GitHub Desktop.
Titlecase Angular 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({ | |
name: 'titlecase' | |
}) | |
export class TitlecasePipe implements PipeTransform { | |
transform(value: any): any { | |
if (!value) { | |
return null; | |
} | |
// short list | |
const prepositions = [ | |
'a', 'an', 'and', 'as', 'at', 'but', 'by', 'en', 'for', 'if', 'in', 'nor', 'of', 'on', 'or', 'per', 'the', 'to', 'via' | |
]; | |
const words = value.split(' '); | |
for (let i = 0; i < words.length; i++) { | |
if (i > 0 && prepositions.includes(words[i].toLowerCase())) { | |
words[i] = words[i].toLowerCase(); | |
} else { | |
words[i] = words[i].substr(0, 1).toUpperCase() + words[i].substr(1).toLowerCase(); | |
} | |
} | |
return words.join(' '); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment