Created
July 2, 2021 02:25
-
-
Save danielkellyio/a80a89e4aa4c820b922c51685cc2ad33 to your computer and use it in GitHub Desktop.
String Helpers Examples
This file contains hidden or 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
| 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