Title Case a string with TypeScript

9.5k views Asked by At

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

There are 3 answers

0
Brocco On BEST ANSWER

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.

0
Kyle On

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.

0
James On

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())
}