Skip to content

Instantly share code, notes, and snippets.

@wffranco
Last active August 1, 2022 16:49
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 wffranco/2fecc900def050bbdd7591a1d98f8e52 to your computer and use it in GitHub Desktop.
Save wffranco/2fecc900def050bbdd7591a1d98f8e52 to your computer and use it in GitHub Desktop.
Case Replacement
/** dash between num-letter */ const dbnl = [/(\d)([a-zA-Z])|([a-zA-Z])(\d)/g, '$1$3-$2$4'];
/** special characters to dash */ const sc2d = [/[^a-zA-Z0-9]+/g, '-'];
/** uppercase to dash */ const u2d = [/([A-Z])/g, '-$1'];
/** Common preconversion */
const commonPre = fn => cacheStringFunction(str => fn(str.replace(...u2d).replace(...dbnl).replace(...sc2d)));
/** dash before a letter */ const dbl = /-([a-zA-Z])/g;
export const capitalizeWords = cacheStringFunction(str => str.toLowerCase().replace(/\b(\w)/g, (_, c) => (c ? c.toUpperCase() : '')));
export const toCamelCase = commonPre(str => str.replace(dbl, (_, c) => (c ? c.toUpperCase() : '')));
export const toKebabCase = commonPre(str => str.toLowerCase());
export const toSnakeCase = commonPre(str => str.replace(dbl, (_, c) => (c ? `_${c}` : '')).toLowerCase());
export const cacheStringFunction = fn => {
const cache = {};
return str => cache[str] || (cache[str] = fn(str));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment