Created
August 8, 2018 20:15
-
-
Save stephenjwatkins/9463c7a3b893d2c97db777740baa8bf0 to your computer and use it in GitHub Desktop.
String utility functions.
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
| const upperCaseFirstLetter = string => { | |
| return string.charAt(0).toUpperCase() + string.slice(1); | |
| }; | |
| const lowerCaseFirstLetter = string => { | |
| return string.charAt(0).toLowerCase() + string.slice(1); | |
| }; | |
| const camelToDashCase = string => { | |
| return lowerCaseFirstLetter(string).replace( | |
| /([A-Z])/g, | |
| g => `-${g[0].toLowerCase()}` | |
| ); | |
| }; | |
| const stringStartsWith = (str, search, pos) => { | |
| return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; | |
| }; | |
| const stringEndsWith = (str, search, length) => { | |
| if (length === undefined || length > str.length) { | |
| length = str.length; | |
| } | |
| return str.substring(length - search.length, length) === search; | |
| }; | |
| const padString = (n, width, z = "0") => { | |
| n += ""; | |
| return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; | |
| }; | |
| const computeStringDifference = (a, b) => { | |
| let startCount = 0; | |
| let endCount = 0; | |
| const bigger = a.length > b.length ? a : b; | |
| for (let i = 0; i < bigger.length; i++) { | |
| if (a[i] === b[i]) { | |
| startCount++; | |
| } else { | |
| break; | |
| } | |
| } | |
| for (let i = 0; i < bigger.length; i++) { | |
| if (a[a.length - 1 - i] === b[b.length - 1 - i]) { | |
| endCount++; | |
| } else { | |
| break; | |
| } | |
| } | |
| return bigger.slice(startCount, bigger.length - endCount); | |
| }; | |
| const removeCharAt = (str, index) => { | |
| return str.slice(0, index) + str.slice(index + 1); | |
| }; | |
| const addCommasToNumber = number => { | |
| const withCommas = number | |
| .toString() | |
| .replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); | |
| return withCommas; | |
| }; | |
| export { | |
| padString, | |
| stringStartsWith, | |
| stringEndsWith, | |
| removeCharAt, | |
| upperCaseFirstLetter, | |
| lowerCaseFirstLetter, | |
| camelToDashCase, | |
| computeStringDifference, | |
| addCommasToNumber, | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment