Skip to content

Instantly share code, notes, and snippets.

@paulakreuger
Last active October 18, 2023 19:34
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save paulakreuger/b2af1958f3d67f46447e to your computer and use it in GitHub Desktop.
Save paulakreuger/b2af1958f3d67f46447e to your computer and use it in GitHub Desktop.
Capitalize First Letter Filter - AngularJS
app.filter('capitalize', function() {
return function(input, scope) {
if (input!=null)
input = input.toLowerCase();
return input.substring(0,1).toUpperCase()+input.substring(1);
}
});
@thomasfrantz
Copy link

Simple and efficient, many thanks :)

@juanpabloaj
Copy link

nice ! thanks a lot

@simonewebdesign
Copy link

Probably worth mentioning that this can be done with one line of CSS:

text-transform: capitalize;

@martininf
Copy link

Actually, what this filter does can not be achieved with CSS. As text-transform: capitalize; won't capitalize when the text is all in uppercase (ie. "JOHN SMITH" or "JoHn SMith" won't transform to "John Smith"). That's why this filter first turns the input to lowercase, before applying the capitalization.

@parambirs
Copy link

Quite useful... thanks!

@ssbrewster
Copy link

I wanted to capitalize the first letter of each word (used in address picker service that was returning everything in uppercase) so implemented the solution from this SO question like so

(function() {
    'use strict';

    angular
        .module('myApp.filters')
        .filter('capitalize', capitalize);

    function capitalize() {
        return filter;

        function filter(input) {
            if (input !== null) {
                return input.replace(/\w\S*/g, function(txt) {
                    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
                });
            }
        }
    }
 })();

@Tzafra
Copy link

Tzafra commented Jun 29, 2015

nice, thanks!

@awemulya
Copy link

app.filter('capitalize', function() {
return function(input, scope) {
if (input!=undefined) {
if (input!=null)
input = input.toLowerCase();
return input.substring(0,1).toUpperCase()+input.substring(1);
}
}
});

use:
{{student.name | capitalize}}

@Jmathieu14
Copy link

@martininf It is possible to do with css, you just need to set the starting css with lowercase, and then you need to use jquery (or plain old javascript) to change the text-transform to uppercase. However, if you are using angular, it may be easier to just use that. Otherwise, this option would be best for those not using angular.

@Jmathieu14
Copy link

I improved the filter so it can handle more than one word (necessary for proper nouns). Here it is:

  .filter('capitalize', function() {
    return function(input, scope) {
      if (input!=null) {
          var stringArr = input.split(" ");
          var result = "";
          var cap = stringArr.length;
          for(var x = 0; x < cap; x++) {
            stringArr[x].toLowerCase();
            if(x === cap - 1) {
              result += stringArr[x].substring(0,1).toUpperCase() + stringArr[x].substring(1);
            } else {
              result += stringArr[x].substring(0,1).toUpperCase() + stringArr[x].substring(1) + " ";
            }
          }
        return result;
      }
    }
  })

@garibo
Copy link

garibo commented Aug 2, 2015

Nice filter 👍

@jdell64
Copy link

jdell64 commented Sep 4, 2015

Great! thanks!

@reichert621
Copy link

adding on to what @simonewebdesign said above, you could also just use angular's built-in lowercase filter and do something like

// CSS
.capitalized { text-transform: capitalize; }

// HTML
<div class="capitalized">{{ data.string | lowercase }}</div>

...to avoid the issues @martininf brought up 😄

@Sampath123
Copy link

app.filter('capitalize', function() {
return function(input, scope) {
if (input!=null)
input = input.toLowerCase();
return input.substring(0,1).toUpperCase()+input.substring(1);
}
});
==>> this wont change JOHN SMITH" or "JoHn SMith" to "John Smith".
It changes to "John smith" instead .

@sunil351
Copy link

sunil351 commented Feb 7, 2016

Thank You!

@Leo24
Copy link

Leo24 commented Feb 7, 2016

Thanks! Very usefull!)))

@tekkemphani
Copy link

@sampath 123 this may help you
`

<script>
    var app = angular.module('myApp', []);
    app.filter('myFilter', function () {
        return function (x) {
            var i,txt = "";
            for (i = 0; i < x.length; i++) {
                if (x[i] == " ") {
                    i++;
                    txt += " "+x[i].toUpperCase(); 
                }
                else {                        
                    txt += x[i];
                }                    
            }
            txt = txt.substring(0, 1).toUpperCase() + txt.substring(1);
            return txt;
        };
    });
    app.controller('namesCtrl', function ($scope) {
        $scope.names = [
            'Jani Wool',
            'Carl',
            'hello margareth',
            'Hege rooman rellex',
            'Joe',
            'Gustav',
            'Birgit',
            'Mary',
            'Kai'
        ];
    });
</script>`

@thiagosbrito
Copy link

What if I do have a string like "state of mind", and I just want "State of Mind", what could I do?

@shakee93
Copy link

shakee93 commented Jun 20, 2016

Might Help Someone. Angular 2 Pipe (aka filter in Angularjs)

@Pipe({name:` 'capitalize'})
export class CapitalizePipe implements PipeTransform {
    transform(value: string): string {
        if (value!=null)
            value = value.toLowerCase();
        return value.substring(0,1).toUpperCase()+value.substring(1);
    }
}

@Teebo
Copy link

Teebo commented Jul 26, 2016

@reichert621 nice one!

@madurapa
Copy link

Thanks bro!

@umairhm
Copy link

umairhm commented Oct 28, 2016

@reichert621: good one ...

@deepshikh
Copy link

deepshikh commented Dec 14, 2016

i have made custom service my html code is:

First word only: {{msg | capitalize}}


All words: {{msg | capitalize:true}}

this is my custom servies js code:

angular.module('MetronicApp', []).
filter('capitalize', function () {
return function (input, all)
{
var reg = (all) ? /([^\W_]+[^\s-]*) /g : /([^\W_]+[^\s-])/;
return (!!input) ? input.replace(reg, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }) : '';
}
});

function seivicesController($scope) {
$scope.msg = 'hello, world.';
}

while i m trying to use in my other controller
code is
$scope.msg = seivicesController.capitalize(input);
stil not getting ans

@tarunwittyfeed
Copy link

return countries.filter(function(country) {
return country.name.toLowerCase().indexOf($query) != -1;

@nagasaikrishna
Copy link

In css add,

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

and use,
class ="capitalize1 capitalize"
in HTML files

@somdey
Copy link

somdey commented Jun 30, 2017

👍

@anilmadala
Copy link

@paula Kreuger
Thanks for nice one and simple filter .

@HarshJains
Copy link

adding on to what @simonewebdesign said above, you could also just use angular's built-in lowercase filter and do something like

// CSS
.capitalized { text-transform: capitalize; }

// HTML
<div class="capitalized">{{ data.string | lowercase }}</div>

...to avoid the issues @martininf brought up 😄

Can you explain me how it works?

@simonewebdesign
Copy link

Can you explain me how it works?

The idea is to convert the string to lower case, then let CSS capitalize each first letter. It can be necessary if you need to prevent the edge cases mentioned by @martininf.

@HarshJains
Copy link

HarshJains commented Jul 26, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment