Browse Source

Add TitleCase Typescript Schnippet

This allows you to convert a string to titlecase.
master
Nate Bohman 4 years ago
parent
commit
561de3ce1f
Signed by: Nate Bohman <natrinicle@gmail.com> GPG Key ID: C10546A54ABA1CE5
1 changed files with 89 additions and 0 deletions
  1. +89
    -0
      typescript_utils/title-case.ts

+ 89
- 0
typescript_utils/title-case.ts View File

// 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…
Cancel
Save