Capitalize the first letter of string in AngularJs

JavascriptAngularjsFilterUppercaseCapitalize

Javascript Problem Overview


I want capitalize first character of string in angularjs

As i used {{ uppercase_expression | uppercase}} it convert whole string to upper case.

Javascript Solutions


Solution 1 - Javascript

use this capitalize filter

var app = angular.module('app', []);

app.controller('Ctrl', function ($scope) {
   $scope.msg = 'hello, world.';
});

app.filter('capitalize', function() {
    return function(input) {
      return (angular.isString(input) && input.length > 0) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() : input;
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div ng-controller="Ctrl">
        <p><b>My Text:</b> {{msg | capitalize}}</p>
    </div>
</div>

Solution 2 - Javascript

I'd say don't use angular/js as you can simply use css instead:

In your css, add the class:

.capitalize {
   text-transform: capitalize;
}

Then, simply wrap the expression (for ex) in your html:

<span class="capitalize">{{ uppercase_expression }}</span>

No js needed ;)

Solution 3 - Javascript

If you use Bootstrap, you can simply add the text-capitalize helper class:

<p class="text-capitalize">CapiTaliZed text.</p>

EDIT: just in case the link dies again:

> Text Transform > >Transform text in components with text capitalization classes. > > lowercased text.
> UPPERCASED TEXT.
> CapiTaliZed Text.
> > html > <p class="text-lowercase">Lowercased text.</p> > <p class="text-uppercase">Uppercased text.</p> > <p class="text-capitalize">CapiTaliZed text.</p> > >Note how text-capitalize only changes the first letter of each word, leaving the case of any other letters unaffected.

Solution 4 - Javascript

If you are using Angular 4+ then you can just use titlecase

{{toUppercase | titlecase}}

don't have to write any pipes.

Solution 5 - Javascript

a nicer way

app.filter('capitalize', function() {
  return function(token) {
      return token.charAt(0).toUpperCase() + token.slice(1);
   }
});

Solution 6 - Javascript

I like the answer from @TrampGuy

CSS is always (well, not always) a better choice, so: text-transform: capitalize; is certainly the way to go.

But what if your content is all uppercase to begin with? If you try text-transform: capitalize; on content like "FOO BAR" you'll still get "FOO BAR" in your display. To get around that issue you could put the text-transform: capitalize; in your css, but also lowercase your string, so:

<ul>
  <li class="capitalize">{{ foo.awesome_property | lowercase }}</li>
</ul>

where we are using @TrampGuy's capitalize class:

.capitalize {
  text-transform: capitalize;
}

So, pretending that foo.awsome_property would normally print "FOO BAR", it will now print the desired "Foo Bar".

Solution 7 - Javascript

If you are after performance, try to avoid using AngularJS filters as they are applied twice per each expression to check for their stability.

A better way would be to use CSS ::first-letter pseudo-element with text-transform: uppercase;. That can't be used on inline elements such as span, though, so the next best thing would be to use text-transform: capitalize; on the whole block, which capitalizes every word.

Example:

var app = angular.module('app', []);

app.controller('Ctrl', function ($scope) {
   $scope.msg = 'hello, world.';
});

.capitalize {
  display: inline-block;  
}

.capitalize::first-letter {
  text-transform: uppercase;
}

.capitalize2 {
  text-transform: capitalize;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div ng-controller="Ctrl">
        <b>My text:</b> <div class="capitalize">{{msg}}</div>
        <p><b>My text:</b> <span class="capitalize2">{{msg}}</span></p>
    </div>
</div>

Solution 8 - Javascript

if you want capitalize each word from string (in progress -> In Progress), you can use array like this.

.filter('capitalize', function() {
    return function(input) {
        return (!!input) ? input.split(' ').map(function(wrd){return wrd.charAt(0).toUpperCase() + wrd.substr(1).toLowerCase();}).join(' ') : '';
    }
});

Solution 9 - Javascript

This is another way:

{{some_str | limitTo:1 | uppercase}}{{some_str.substr(1) | lowercase }}

Solution 10 - Javascript

For Angular 2 and up, you can use {{ abc | titlecase }}.

Check Angular.io API for complete list.

Solution 11 - Javascript

<span class="capitalize">
  really, once upon a time there was a badly formatted output coming from my backend, <strong>all completely in lowercase</strong> and thus not quite as fancy-looking as could be - but then cascading style sheets (which we all know are <a href="http://9gag.com/gag/6709/css-is-awesome">awesome</a>) with modern pseudo selectors came around to the rescue...
</span>

.capitalize {
  display: inline-block;
}

.capitalize:first-letter {
  font-size: 2em;
  text-transform: capitalize;
}

Solution 12 - Javascript

In angular 7+ which has built-in pipe

{{ yourText | titlecase  }}

Solution 13 - Javascript

For the AngularJS from meanjs.org, I place the custom filters in modules/core/client/app/init.js

I needed a custom filter to capitalize each word in a sentence, here is how I do so:

angular.module(ApplicationConfiguration.applicationModuleName).filter('capitalize', function() {
return function(str) {
    return str.split(" ").map(function(input){return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() :         ''}).join(" ");
  
}
});

The credit of the map function goes to @Naveen raj

Solution 14 - Javascript

If you don't want to build custom filter then you can use directly

{{ foo.awesome_property.substring(0,1) | uppercase}}{{foo.awesome_property.substring(1)}}

Solution 15 - Javascript

var app = angular.module("app", []);
app.filter('capitalize', function() {
    return function(str) {
        if (str === undefined) return; // avoid undefined
        str = str.toLowerCase().split(" ");
        var c = '';
        for (var i = 0; i <= (str.length - 1); i++) {
            var word = ' ';
            for (var j = 0; j < str[i].length; j++) {
                c = str[i][j];
                if (j === 0) {
                    c = c.toUpperCase();
                }
                word += c;
            }
            str[i] = word;
        }
        str = str.join('');
        return str;
    }
});

Solution 16 - Javascript

Just to add my own take on this issue, I would use a custom directive myself;

app.directive('capitalization', function () {
return {
    require: 'ngModel',
    link: function (scope, element, attrs, modelCtrl) {

        modelCtrl.$parsers.push(function (inputValue) {

            var transformedInput = (!!inputValue) ? inputValue.charAt(0).toUpperCase() + inputValue.substr(1).toLowerCase() : '';

            if (transformedInput != inputValue) {
                modelCtrl.$setViewValue(transformedInput);
                modelCtrl.$render();
            }

            return transformedInput;
        });
    }
};

Once declared you can place inside your Html as below;

<input ng-model="surname" ng-trim="false" capitalization>

Solution 17 - Javascript

Instead if you want to capitalize each word of a sentence then you can use this code

app.filter('capitalize', function() {


return function(input, scope) {
if (input!=null)
input = input.toLowerCase().split(' ');

for (var i = 0; i < input.length; i++) {
   // You do not need to check if i is larger than input length, as your for does that for you
   // Assign it back to the array
   input[i] = input[i].charAt(0).toUpperCase() + input[i].substring(1);     


}
   // Directly return the joined string
   return input.join(' '); 
  }
});

and just add filter "capitalize" to your string input, for ex - {{name | capitalize}}

Solution 18 - Javascript

in Angular 4 or CLI you can create a PIPE like this:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'capitalize'
})
/**
 * Place the first letter of each word in capital letters and the other in lower case. Ex: The LORO speaks = The Loro Speaks
 */
export class CapitalizePipe implements PipeTransform {
  transform(value: any): any {
    value = value.replace('  ', ' ');
    if (value) {
      let w = '';
      if (value.split(' ').length > 0) {
        value.split(' ').forEach(word => {
          w += word.charAt(0).toUpperCase() + word.toString().substr(1, word.length).toLowerCase() + ' '
        });
      } else {
        w = value.charAt(0).toUpperCase() + value.toString().substr(1, value.length).toLowerCase();
      }
      return w;
    }
    return value;
  }
}

Solution 19 - Javascript

Angular has 'titlecase' which capitalizes the first letter in a string

For ex:

envName | titlecase

will be displayed as EnvName

When used with interpolation, avoid all spaces like

{{envName|titlecase}}

and the first letter of value of envName will be printed in upper case.

Solution 20 - Javascript

if (value){
  value = (value.length > 1) ? value[0].toUpperCase() + value.substr(1).toLowerCase() : value.toUpperCase();
}

Solution 21 - Javascript

You can try to split your String into two parts and manage their case separately.

{{ (Name.charAt(0) | uppercase) + "" + (Name.slice(1, element.length) | lowercase) }}

or

{{ Name.charAt(0) | uppercase }} {{ Name.slice(1, element.length) | lowercase  }}

Solution 22 - Javascript

You can add capitalize functionality run time as:

<td>{{lastName.charAt(0).toUpperCase()+ lastName.substr(1).toLowerCase()}}</td>

Solution 23 - Javascript

{{ uppercase_expression | capitaliseFirst}} should work

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPiyushView Question on Stackoverflow
Solution 1 - JavascriptNidhish KrishnanView Answer on Stackoverflow
Solution 2 - JavascriptTrampGuyView Answer on Stackoverflow
Solution 3 - JavascriptminimalpopView Answer on Stackoverflow
Solution 4 - JavascriptAbhishek EkaanthView Answer on Stackoverflow
Solution 5 - JavascriptPatrik MelanderView Answer on Stackoverflow
Solution 6 - JavascriptRyan CrewsView Answer on Stackoverflow
Solution 7 - JavascriptGregor EesmaaView Answer on Stackoverflow
Solution 8 - JavascriptNaveen rajView Answer on Stackoverflow
Solution 9 - Javascriptpallav deshmukhView Answer on Stackoverflow
Solution 10 - JavascriptwindmaomaoView Answer on Stackoverflow
Solution 11 - JavascriptPhilzenView Answer on Stackoverflow
Solution 12 - JavascriptAhmad SharifView Answer on Stackoverflow
Solution 13 - JavascriptMaxim MaiView Answer on Stackoverflow
Solution 14 - JavascriptKshitijView Answer on Stackoverflow
Solution 15 - Javascriptmurali2486View Answer on Stackoverflow
Solution 16 - Javascriptuk2k05View Answer on Stackoverflow
Solution 17 - JavascriptAkash SaxenaView Answer on Stackoverflow
Solution 18 - JavascripteberlastView Answer on Stackoverflow
Solution 19 - JavascriptVedha PeriView Answer on Stackoverflow
Solution 20 - JavascriptAliView Answer on Stackoverflow
Solution 21 - JavascriptPriteshView Answer on Stackoverflow
Solution 22 - JavascriptRahul MankarView Answer on Stackoverflow
Solution 23 - JavascriptHasan ShaikView Answer on Stackoverflow