我有一些大的 table.column 名称需要缩写。或者更确切地说,表名需要缩写。
采用以下 table.col 名称示例及其外观:
agentByState5Minutes.agentId ----> aBS5M.agentId
contactReasonByMail.agentName -----> cRBM.agentName
正如您在上面看到的,表名称是大小写和数字的混合。在我的函数中,我将表名与列名分开,以使其更容易:
protected columnNameConvert(colName: string): string{
this.log.info('columnNameConvert:colName:'+ colName);
let colNameSplit: Array<string> = colName.split('.');
let tableName: string = colNameSplit[0];
let realColName: string = colNameSplit[1];
return colName;
}
可以使用正则表达式文本操作来缩写 tableName 吗?
最佳答案
我会使用 replace
来匹配除大写字母、数字或字符串开头以外的任何内容,同时向前查找 。
并(在开始时)检查该位置是否不在字符串的开头:
const change = str => str.replace(
/(?!^)[^A-Z\d](?=[^.]*\.)/g,
''
);
console.log(
change('agentByState5Minutes.agentId'), // ----> aBS5M.agentId
change('contactReasonByMail.agentName') // -----> cRBM.agentName
);
(?!^)[^A-Z\d](?=[^.]*\.)
表示:
(?!^)
- 字符串开头的负向前瞻(确保匹配的位置不在字符串的开头)[^A-Z\d]
- 除大写字母或数字外的任何内容(?=[^.]*\.)
- 确保匹配的字符最终后面跟着.
在 typescript 语法中:
const columnNameConvert = (colName: string) => colName.replace(
/(?!^)[^A-Z\d](?=[^.]*\.)/g,
'',
);
(请记住,如果 TS 可以自行推断返回类型,则无需显式指示返回类型)
关于javascript - 如何在 TypeScript/JavaScript 中缩写驼峰式文本字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57216356/