|
- // 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;
- };
|