titlecase的代码非常直接,没有自定义!
// #docregion
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'titlecase', standalone: true, pure: true })
/** Transform to Title Case: uppercase the first letter of the words in a string. */
export class TitleCasePipe implements PipeTransform {
transform(input: string): string {
return input.length === 0
? ''
: input.replace(/\w\S*/g, (txt) => txt[0].toUpperCase() + txt.slice(1).toLowerCase());
}
}
只是go 后转换,做一个正则表达式替换白名单关键字!
下面的例子!
import { CommonModule, TitleCasePipe } from '@angular/common';
import { Component, Self } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
providers: [TitleCasePipe],
template: `
<h1>Hello from {{ name }}!</h1>
<a target="_blank" href="https://angular.dev/overview">
Learn more about Angular
</a>
`,
})
export class App {
name = 'Angular';
constructor(@Self() private titleCasePipe: TitleCasePipe) {}
ngOnInit() {
const obj = {
Draft: 19,
'Process Model QA review in progress': 22,
'Process Model QA Rejected': 17,
'Process Model QA Approved': 13,
'Process Owner review in progress': 28,
Approved: 22,
'Opt-out': 3,
'Process Owner Rejected': 4,
'Process Owner Approved': 10,
'Soln. Architect review in progress': 4,
'Soln. Architect Rejected': 4,
Cancelled: 10,
};
const arr: any = [];
Object.entries(obj).map((elem) => {
arr.push({
id: elem[0],
name: this.safeTransform(elem[0]) + ' (' + elem[1] + ')',
});
});
console.log(arr);
}
safeTransform(elem: any) {
let output = this.titleCasePipe.transform(elem);
// whitelist
['QA'].forEach((regexKey) => {
var re = new RegExp(regexKey, 'gi');
output = output.replace(re, regexKey);
});
return output;
}
}
bootstrapApplication(App);
Stackblitz Demo