Skip to content

Instantly share code, notes, and snippets.

@danielkellyio
Created July 2, 2021 02:25
Show Gist options
  • Select an option

  • Save danielkellyio/a80a89e4aa4c820b922c51685cc2ad33 to your computer and use it in GitHub Desktop.

Select an option

Save danielkellyio/a80a89e4aa4c820b922c51685cc2ad33 to your computer and use it in GitHub Desktop.
String Helpers Examples
export const ucFirst = (string)=>{
if (typeof string !== 'string') return ''
return string.charAt(0).toUpperCase() + string.slice(1)
}
export const ucWords = (string) =>{
if (typeof string !== 'string') return ''
return string.split(' ').map(word => ucFirst(word)).join(' ')
}
export const snakeCase = (string) =>{
return string.replace(/-/g, '_').replace(/ /g, '_').replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`).replace(/^_/, '')
}
export const camelCase = (string)=>{
return snakeCase(string).replace(/_./g, letter => letter.toUpperCase().replace('_', ''))
}
export const sentenceCase = (string)=>{
return ucFirst(snakeCase(string).split('_').join(' '))
}
export const titleCase = (string)=>{
const blacklist = ['a', 'an', 'and', 'the', 'is', 'are', 'has','and', 'as', 'at', 'but', 'by', 'for', 'from', 'if', 'in', 'into', 'like', 'near', 'that', 'nor', 'of', 'off', 'on', 'once', 'onto', 'or', 'over', 'past', 'so', 'than', 'that', 'till', 'to', 'up', 'upon', 'with', 'when', 'yet']
return sentenceCase(string).split(' ').map(word => blacklist.includes(word) ? word : ucFirst(word)).join(' ')
}
export const phoneNumberFormatted = (phoneNumberString, seperator=null) => {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
if (match) {
if(!seperator) return `(${match[1]}) ${match[2]} - ${match[3]}`
return `${match[1]}${seperator}${match[2]}${seperator}${match[3]}`
}
return null
}
export const nestedFromDot = (object, string)=>{
return string.split('.').reduce((o,i)=>o[i], object)
}
export const nestedToDot = (object, string, value)=>{
const props = string.split('.')
let level = object
let prevProp = null
props.forEach(prop => {
level = level[prop]
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment