我正在尝试编写一个函数来更正名称输入,因此如果用户输入:mohamed ahmed,输出将是 Mohamed Ahmed。
我添加了这个过滤器:
app.filter('properName', function () {
return function (x) {
var newName = '';
newName += x[0].toUpperCase();
for (var i = 1; i < x.length; i++) {
if (x[i] == ' ') {
newName += ' ';
newName += x[i + 1].toUpperCase();
}
else {
newName += x[i].toLowerCase();
}
}
return newName;
}
});
但是当我输入任何输入时,空格后的字母是重复的;一个大写,一个小写:
var app = angular.module('myApp', []).filter('properName', function () {
return function (x) {
var newName = '';
newName += x[0].toUpperCase();
for (var i = 1; i < x.length; i++) {
if (x[i] == ' ') {
newName += ' ';
newName += x[i + 1].toUpperCase();
}
else {
newName += x[i].toLowerCase();
}
}
return newName;
}
});;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="myApp">
PN: <input type="text" ng-model="name" ng-bind="n"/>
Proper Name: <h3 ng-bind="name | properName"></h3>
</div>
最佳答案
尝试改变
if (x[i] == ' ') {
newName += ' ';
newName += x[i + 1].toUpperCase();
}
到
if(i && x[i-1] ==' ' ){
newName += x[i].toUpperCase();
}
当 x[i]
是空格时,它可以毫无问题地小写。在真正到达空格后的字符之前,您不想进行调整
关于javascript - 使用 JavaScript 和 Angularjs 返回正确名称大小写的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41322662/