我需要制作一个角度过滤器,它将采用全名,并初始化名字,只留下姓氏,除非在某些情况下(例如Van Aanholt)。
以下内容:
Yohan Cabaye
Oscar
Jordi Alba Ramos
Patrick Van Aanholt
Hatem Ben Arfa
将显示为:
Y. Cabaye
Oscar
J. Ramos
P. Van Aanholt
H. Ben Arfa
任何帮助都将不胜感激。
更新:这是我尝试过的......
angular.module('euroFilters', [])
.filter('initialiseName', function() {
return function(name) {
var nameArr = name.split(' ');
var firstName = nameArr[0];
var firstNameInitial = nameArr[0][0] + ". ";
var lastName = nameArr[nameArr.length - 1];
var secondaryLastName = nameArr[nameArr.length - 2];
// If only one name (standard)...
if (nameArr.length <= 1) {
return firstName;
}
// If more than one name, and contains "Van" or "Ben" (exception)...
else if (secondaryLastName === "Van" || secondaryLastName === "Ben") {
return firstNameInitial + " " + secondaryLastName + " " + lastName;
}
// If more than one name (standard)...
else if (nameArr.length > 1) {
return firstNameInitial + lastName;
}
};
});
有更优雅的方式来写这个吗?例如,它如何转换为switch
语句?
答案 0 :(得分:1)
您可以使用拆分和连接。 String是类似于对象的数组,因此您可以对它们使用索引。
angular.module('app', []);
angular.module('app').filter('initialiseFirstName', function () {
return function (name) {
var parts = name.split(/\s+/);
if (parts.length <= 1) {
return name;
}
var first = parts[0][0] + '.';
return first + ' ' + parts.slice(1).join(' ');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
{{'John Ket'|initialiseFirstName}}
</div>
答案 1 :(得分:0)
这应该做你需要的:
<div ng-app="app">
{{'John Von Koten'|initialiseFirstName}}
</div>
<script>
angular.module('app', []);
angular.module('app').filter('initialiseFirstName', function () {
function checkName(name){
var prefixes = ['Van', 'Ben', 'Von'];
for(var i = 0; i < prefixes.length; i++){
if(name.indexOf(prefixes[i]) > 0){
return true;
}
}
return false;
}
return function (name) {
var parts = name.split(/\s+/);
if (parts.length <= 1) {
return name;
}
if(parts.length > 2){
if(checkName(name)){
return parts[0][0] + '. ' + parts[1] + ' '+ parts[2];
}
}
var first = parts[0][0] + '.';
return first + ' ' + parts.slice(1).join(' ');
}
});
</script>