瀏覽代碼

Add TitleCase Typescript Schnippet

This allows you to convert a string to titlecase.
master
Nate Bohman 4 年之前
父節點
當前提交
561de3ce1f
簽署人: Nate Bohman <natrinicle@gmail.com> GPG Key ID: C10546A54ABA1CE5
共有 1 個文件被更改,包括 89 次插入0 次删除
  1. +89
    -0
      typescript_utils/title-case.ts

+ 89
- 0
typescript_utils/title-case.ts 查看文件

@@ -0,0 +1,89 @@
// Standalone function
export const toTitleCase = function(str: string): string {
str = str.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});

// Certain minor words should be left lowercase unless
// they are the first or last words in the string
const lowers = [
'A',
'An',
'And',
'As',
'At',
'But',
'By',
'For',
'From',
'In',
'Into',
'Is',
'Near',
'Nor',
'Of',
'On',
'Onto',
'Or',
'The',
'To',
'With',
];
const uppers = ['Id', 'Tv'];

for (let i = 0; i < lowers.length; i++)
str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) {
return txt.toLowerCase();
});

// Certain words such as initialisms or acronyms should be left uppercase
for (let i = 0; i < uppers.length; i++)
str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase());

return str;
};

// Prototype onto String so any string gets "".toTitleCase()
String.prototype.toTitleCase = function() {
let str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});

// Certain minor words should be left lowercase unless
// they are the first or last words in the string
const lowers = [
'A',
'An',
'And',
'As',
'At',
'But',
'By',
'For',
'From',
'In',
'Into',
'Is',
'Near',
'Nor',
'Of',
'On',
'Onto',
'Or',
'The',
'To',
'With',
];
const uppers = ['Id', 'Tv'];

for (let i = 0; i < lowers.length; i++)
str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) {
return txt.toLowerCase();
});

// Certain words such as initialisms or acronyms should be left uppercase
for (let i = 0; i < uppers.length; i++)
str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase());

return str;
};

Loading…
取消
儲存