AngularJs 中字符串首字母大写

Capitalize the first letter of string in AngularJs

我想在 angularjs

中将字符串的第一个字符大写

因为我使用 {{ uppercase_expression | uppercase}} 它将整个字符串转换为大写。

使用这个大写过滤器

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>

更好的方式

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

如果你想将字符串中的每个单词大写 (in progress -> In Progress),你可以像这样使用数组。

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

对于 meanjs.org 中的 AngularJS,我将自定义过滤器放在 modules/core/client/app/init.js

我需要一个自定义过滤器来将句子中的每个单词大写,我是这样做的:

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

}
});

地图函数归功于@Naveen raj

如果您追求性能,请尽量避免使用 AngularJS 过滤器,因为每个表达式应用两次过滤器以检查其稳定性。

更好的方法是使用 CSS ::first-letter pseudo-element 和 text-transform: uppercase;。但是,它不能用于内联元素,例如 span,所以下一个最好的办法是在整个块上使用 text-transform: capitalize;,这会将每个单词都大写。

示例:

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>

为了补充我对这个问题的看法,我自己会使用自定义指令;

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

声明后,您可以将其放入 Html 中,如下所示;

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

我会说不要使用 angular/js 因为你可以简单地使用 css 来代替:

在您的 css 中,添加 class:

.capitalize {
   text-transform: capitalize;
}

然后,只需将表达式(for ex)包装在 html:

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

不需要 js ;)

我喜欢@TrampGuy 的回答

CSS 总是(嗯,不总是)更好的选择,所以:text-transform: capitalize; 肯定是正确的选择。

但是,如果您的内容全部以大写开头怎么办?如果您对 "FOO BAR" 等内容尝试 text-transform: capitalize;,您仍然会在显示中看到 "FOO BAR"。要解决该问题,您可以将 text-transform: capitalize; 放在 css 中,但也可以将字符串小写,因此:

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

我们使用@TrampGuy 的大写 class:

.capitalize {
  text-transform: capitalize;
}

所以,假装 foo.awsome_property 通常会打印 "FOO BAR",它现在会打印所需的 "Foo Bar"。

相反,如果您想将句子中的每个单词大写,则可以使用此代码

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(' '); 
  }
});

只需将过滤器 "capitalize" 添加到您的字符串输入中,例如 - {{name |大写}}

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

如果你使用 Bootstrap, you can simply add the text-capitalize 助手 class:

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

编辑:以防万一 link 再次死亡:

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.

如果您不想构建自定义过滤器,那么您可以直接使用

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

您可以添加大写功能 运行 时间为:

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

{{ uppercase_expression | capitaliseFirst}} 应该有效

在 Angular 4 或 CLI 中,您可以像这样创建一个 PIPE:

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

对于 Angular 2 岁及以上,您可以使用 {{ abc | titlecase }}

检查 Angular.io API 以获得完整列表。

这是另一种方式:

{{some_str | limitTo:1 | uppercase}}{{some_str.substr(1) | lowercase }}
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;
    }
});

如果您使用的是 Angular 4+,那么您可以只使用 titlecase

{{toUppercase | titlecase}}

不必编写任何管道。

Angular 有 'titlecase' 将字符串中的第一个字母大写

例如:

envName | titlecase

将显示为 EnvName

与插值一起使用时,避免所有空格,如

{{envName|titlecase}}

并且envName的值的第一个字母将以大写形式打印。

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

在 angular 7+ 中内置 pipe

{{ yourText | titlecase  }}

您可以尝试将您的字符串分成两部分并分别管理它们的大小写。

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

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