1

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?

3 Answers3

0

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.

Brocco
  • 62,737
  • 12
  • 70
  • 76
0

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.

Kyle
  • 199
  • 1
  • 3
0

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())
}
James
  • 31
  • 4