Reputation:
Do TypeScript provide any built in methods on strings to capitalize or Title case a string?
I am aware of the methods toLocaleLowerCase()
, LowerCase()
, toLocaleUpperCase()
and UpperCase()
. Does TypeScript has another case convertion methods?
Upvotes: 1
Views: 10982
Reputation: 303
There's about 40 prepositions, but this example only include a few for the example:
TitleCase(value: string): any {
if (!value) return null;
let words = value.split(' ');
for (let i=0; i < words.length; i++) {
let word = words[i];
// skip first word preposition
if (i > 0 && this.isPreposition(word))
words[i] = word.toLowerCase();
else
words[i] = this.toTitleCase(word);
}
return words.join(' ');
}
private toTitleCase(word:string):string {
return word.substring(0,1).toUpperCase() +
word.substring(1).toLowerCase();
}
private isPreposition(word:string):boolean {
let prepositions = ['if','the','a','on','in','of','or','and'];
return prepositions.includes(word.toLowerCase())
}
Upvotes: 1
Reputation: 319
Do TypeScript provide any built in methods on strings to capitalize or Title case a string?
Not that I am aware.
Check out how the Angular team did it for their TitleCasePipe using TypeScript.
Upvotes: 1
Reputation: 64863
There are no additional methods or API's in TypeScript that can not be found in JavaScript.
I'm sure you can find either an npm package or sample code to title case a string in JavaScript which can be used via TypeScript.
Upvotes: 1