Quellcode durchsuchen

Add TitleCase Typescript Schnippet

This allows you to convert a string to titlecase.
master
Nate Bohman vor 4 Jahren
Ursprung
Commit
561de3ce1f
Signiert von: Nate Bohman <natrinicle@gmail.com> GPG-Schlüssel-ID: C10546A54ABA1CE5
1 geänderte Dateien mit 89 neuen und 0 gelöschten Zeilen
  1. +89
    -0
      typescript_utils/title-case.ts

+ 89
- 0
typescript_utils/title-case.ts Datei anzeigen

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

Laden…
Abbrechen
Speichern