Skip to content

Instantly share code, notes, and snippets.

@ademidun
Created August 5, 2020 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ademidun/8fb2752617789367ac23514b9721fad5 to your computer and use it in GitHub Desktop.
Save ademidun/8fb2752617789367ac23514b9721fad5 to your computer and use it in GitHub Desktop.
Useful javascript utility functions to make your life easier.
function prettifyKeys(rawKey) {
return toTitleCase(rawKey.replace(/_/g, ' ' ));
}
function toTitleCase(str) {
var i, j, lowers, uppers;
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
lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At',
'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
for (i = 0, j = lowers.length; i < j; 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
uppers = ['Id', 'Tv'];
for (i = 0, j = uppers.length; i < j; i++) {
str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'),
uppers[i].toUpperCase());
}
return str;
}
function formatCurrency(input) {
return input.toLocaleString('en-ca', {style : 'currency', currency: 'CAD'});
}
function slugify(text) {
return text
.trim()
.toLowerCase()
.replace(/[^\w /-]+/g, '')
.trim()
.replace(/ +/g, '-')
.replace(/\//g, '-')
.replace(/-{2,}/g, '-')
;
}
export function unSlugify(str) {
if(!str) {
return str
}
return toTitleCase(str.replace(/-/g, " ").replace(/\+/g, " "));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment