Created
August 5, 2020 20:33
-
-
Save ademidun/8fb2752617789367ac23514b9721fad5 to your computer and use it in GitHub Desktop.
Useful javascript utility functions to make your life easier.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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