144

I want capitalize first character of string in angularjs

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

Alex Man
  • 4,746
  • 17
  • 93
  • 178
Piyush
  • 3,947
  • 9
  • 36
  • 69
  • 1
    Yes, you'll have to write some code. Angular won't do *everything* for you. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase – JB Nizet May 13 '15 at 06:34
  • 12
    This can be done using CSS also.. Check out the text-transform: capitalize property – Ramanathan Muthuraman May 13 '15 at 06:35
  • 1
    You can use this solution if you really want to use angular : http://codepen.io/WinterJoey/pen/sfFaK – Yousef_Shamshoum May 13 '15 at 06:36
  • 1
    create a simple directive/filter that will make first letter of word capital for you... – Pankaj Parkar May 13 '15 at 06:36

24 Answers24

236

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>
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
  • 11
    You get an error if you want to capitalize a number accidentally. The body of the function should be this: `return (angular.isString(s) && s.length > 0) ? s[0].toUpperCase() + s.substr(1).toLowerCase() : s;` . If it's not a string then return it unchanged. – Jabba Dec 05 '15 at 12:46
  • 2
    Here is written the custom capitalization filter https://codepen.io/WinterJoey/pen/sfFaK – Skyware Mar 06 '17 at 20:52
159

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 ;)

TacoEater
  • 2,115
  • 20
  • 22
TrampGuy
  • 1,737
  • 1
  • 13
  • 9
  • 9
    This transform will capitalize ***First Letter Of Each Word*** so is only applicable to one-word strings – jakub.g Aug 02 '16 at 09:28
  • 25
    @jakub.g If your just want to capitalize the first word (well, letter), simply expland the css selector with the `:first-letter` pseudo-element selector. Anything else left uncovered? :) – Philzen Aug 24 '16 at 01:50
  • 2
    @Philzen Yes ! How would you do it with html only ? ;-) – Romain Vincent Feb 10 '17 at 22:59
  • @RomainVincent What do you mean by "HTML only"? Maybe my [answer below](http://stackoverflow.com/questions/30207272/capitalize-the-first-letter-of-string-in-angularjs/39113339#39113339) helps (just click "Run code snippet" to see it in action). HTML content is static, you will at least need to throw in some CSS or JS to modify its styling, respectively DOM content. – Philzen Mar 08 '17 at 21:45
  • 4
    I'm sorry, that was a bad attempt at making a joke. – Romain Vincent Mar 08 '17 at 23:33
  • This is generally a good idea, but if I want to process the capitalized string any further with Angular, JavaScript/Angular would still treat it as a non-capitalized string. – Lea Reimann Mar 10 '19 at 11:24
59

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.

<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.

Vardkin
  • 110
  • 3
  • 4
minimalpop
  • 6,997
  • 13
  • 68
  • 80
31

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

{{toUppercase | titlecase}}

don't have to write any pipes.

Abhishek Ekaanth
  • 2,511
  • 2
  • 19
  • 40
  • 7
    This is an incorrect answer—the question asks to capitalise the first letter of the string, not the first letter of every word. – Alex Peters Nov 06 '18 at 02:15
24

a nicer way

app.filter('capitalize', function() {
  return function(token) {
      return token.charAt(0).toUpperCase() + token.slice(1);
   }
});
Community
  • 1
  • 1
Patrik Melander
  • 585
  • 3
  • 7
20

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".

Ryan Crews
  • 3,015
  • 1
  • 32
  • 28
18

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>
Gregor Eesmaa
  • 1,206
  • 1
  • 14
  • 22
  • 1
    Unfortunately `::first-letter` doesn't work on `display: inline` or `display: flex`, only on `display:block` or `inline-block` elements – jakub.g Aug 02 '16 at 09:35
14

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(' ') : '';
    }
});
Naveen raj
  • 891
  • 1
  • 10
  • 18
13

This is another way:

{{some_str | limitTo:1 | uppercase}}{{some_str.substr(1) | lowercase }}
Styx
  • 9,863
  • 8
  • 43
  • 53
pallav deshmukh
  • 243
  • 1
  • 4
  • 6
9

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

Check Angular.io API for complete list.

Roadirsh
  • 571
  • 5
  • 23
windmaomao
  • 7,120
  • 2
  • 32
  • 36
  • 1
    This is an incorrect answer—the question asks to capitalise the first letter of the string, not the first letter of every word. – Alex Peters Nov 06 '18 at 02:15
7

.capitalize {
  display: inline-block;
}

.capitalize:first-letter {
  font-size: 2em;
  text-transform: capitalize;
}
<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>
Philzen
  • 3,945
  • 30
  • 46
4

In angular 7+ which has built-in pipe

{{ yourText | titlecase  }}
Ahmad Sharif
  • 4,141
  • 5
  • 37
  • 49
3

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

Maxim Mai
  • 145
  • 5
  • 14
2

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)}}
kshitij
  • 614
  • 9
  • 18
2
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;
    }
});
Ken007
  • 67
  • 1
  • 4
murali2486
  • 21
  • 2
  • 2
    While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – peacetype Jan 20 '18 at 07:19
1

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>
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
uk2k05
  • 368
  • 2
  • 9
1

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

Akash Saxena
  • 147
  • 2
  • 11
0

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;
  }
}
eberlast
  • 160
  • 2
  • 7
0

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.

Vedha Peri
  • 1,386
  • 2
  • 12
  • 11
0
if (value){
  value = (value.length > 1) ? value[0].toUpperCase() + value.substr(1).toLowerCase() : value.toUpperCase();
}
Ali
  • 125
  • 2
  • 4
0

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  }}
Lomefin
  • 1,173
  • 12
  • 43
Pritesh
  • 1
  • 1
0

{{ uppercase_expression.substr(0,1).toUpperCase() + uppercase_expression.substr(1) }}

Ashik T M
  • 23
  • 1
  • 7
-1

You can add capitalize functionality run time as:

<td>{{lastName.charAt(0).toUpperCase()+ lastName.substr(1).toLowerCase()}}</td>
Rahul Mankar
  • 910
  • 9
  • 17
-1

{{ uppercase_expression | capitaliseFirst}} should work

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Hasan Shaik
  • 109
  • 1
  • 2