'Capitalize the first word (or optionally all the words) of a sentence in angular 2+

I am trying to capitalize words of a string in the angular 2 template (aka view) but I get the following error in the console and the application does not load (displays a blank page):

Error: Uncaught (in promise): Error: Template parse errors: The pipe 'capitalize' could not be found

I am trying to do the following. The below examples use a literal string for illustration. In reality, the string will be a variable in the angular 2 component.

  1. Capitalize only the first word of the sentence if no argument is provided.
 {{ 'heLlo woRld' | capitalize }} // outputs "HeLlo woRld" - Only "H" is capitalized
  1. Capitalize all words of the string by passing the argument 'all'.

{{ 'heLlo woRld' | capitalize:'all' }} // outputs "HeLlo WoRld" - Both "H" and "W" are capitalized

  1. Some other edge cases that are to be satisfied are:
 {{ 'a' | capitalize }}                   // outputs "A"

 {{ 'a' | capitalize:'all' }}             // outputs "A"

 {{ '' | capitalize }}                    // outputs nothing

 {{ '' | capitalize:'all' }}              // outputs nothing

 {{ null | capitalize }}                  // outputs nothing

 {{ null | capitalize:'all' }}            // outputs nothing

NOTE: Please note that solution should be pure JS based (no csss) and does not have to be unicode compliant, but should conform to best practices, and particularly:

  1. NO THIRD PARTY LIBRARY(such as jQuery, underscore, lodash) should be used
  2. AND code should conform to both Typescript and ES6 standards.

NOTE: Removed the phrase "No ES3 or ES5 code" as this phrase was causing some confusion and also added the error that I was getting.



Solution 1:[1]

I had assumed that angular 2 provides a "capitalize" pipe out of the box (just as it provides the "uppercase" pipe). So, to resolve the problem, created a "capitalize" pipe as follows:

  1. Create a file called: capitalize.pipe.ts

Alternately, if you are using angular-cli, then you can generate the above file using the command: ng g pipe capitalize

NOTE: You will also have to modify your modulg file(e.g. home.module.ts) to include the newly created/generated pipe.

  1. Modify the newly created/generated file as follows:
import { Pipe, PipeTransform } from '@angular/core';

// To be DRY, define a reusable function that converts a 
// (word or sentence) to title case

const toTitleCase = (value) => {
  return value.substring(0, 1).toUpperCase() + value.substring(1);
  // alternately, can also use this: 
  // return value.charAt(0).toUpperCase() + value.slice(1);
};

@Pipe({
  name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {

  transform(value: any, args?: any): any {
    if (value) {
      if (args === 'all') {
        return value.split(' ').map(toTitleCase).join(' ');
      } else {
        return toTitleCase(value);
      }
    }
    return value;
  }

}
  1. Once you have done the above, then you can use the pipe from your template (aka view) as follows:

{{ 'heLlo woRld' | capitalize }} // outputs "HeLlo woRld" - Only "H" is capitalized

{{ 'heLlo woRld' | capitalize:'all' }} // outputs "HeLlo WoRld" - Both "H" and "W" are capitalized

Solution 2:[2]

it will capitalize first letter of each word :

function cap_words(str){
    str=str.split(" ")
    for(var i=0 ; i<str.length ;i++){
        str[i]= str[i][0].toUpperCase()+str[i].substring(1)
    }
    return str.join(" ")
}


console.log(cap_words("and this is a test !"))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sajjad cheraghi