Q:

Angular - TitleCase - Can we have words like 'in' non-capitalised?

I have seen TitleCase used for capitalizing each word of a string which is useful, however...
I am wanting to output movie titles that have been stored as all lowercase. I could use TitleCase, but this would not give the appearance that people usually expect.
For example, the movie title (in lowercase):

the assassination of jesse james by the coward robert ford

I could use TitleCase for output:

The Assassination Of Jesse James By The Coward Robert Ford.

However when seen in print in either magazine or on movie posters the O and B of 'of' and 'by' are never capitalized.
Is there a simple method by which I can get the look I am wanting to achieve, other than simply using {{movie.title | titlecase}}?
I know that I could create a dictionary and search for the keywords within the strings, but I am wanting something potentially simpler...

A:

You could write your own pipe that capitalizes every word EXCEPT the ones you don't want capitalized.
import { Pipe, PipeTransform } from '@angular/core'

@Pipe({ name: 'titleCaseExcept' })
export class TitleCaseExceptPipe implements PipeTransform {
  transform(value: string): string {
    if (!value) return value; // safeguard

    // regex to find all words EXCEPT the ones we don't want capitalized
    let words: RegExp = /\b(?!of|by|the)\w+/g;
    // capitalize the first letters of said words
    let newVal = value.replace(words, (match) => {
      return match.replace(/^\w/, (word) => word.charAt(0).toUpperCase() + word.substr(1).toLowerCase());
    })

    // always capitalize the first character of newVal
    return newVal.charAt(0).toUpperCase() + newVal.substr(1);
  }
}

Add words you would like excluded to the regex as you see fit.

