UNPKG

@zodash/snake-case

Version:

Convert (camelCase) string to snakeCase.

31 lines (30 loc) 919 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.compose = exports.snakeCase = void 0; const camelCasePattern = '([A-Z]?[a-z]+)'; const snakeCasePattern = '([a-zA-Z]+)'; const pattern = new RegExp(`${camelCasePattern}|${snakeCasePattern}`, 'g'); function words(value) { return value.match(pattern); } /** * Converts a string value into [snake case](https://en.wikipedia.org/wiki/Snake_case). * @param value The string to convert. * @returns The snake-cased string. * @example ```ts * snakeCase('fooBarBaz') * // => 'foo_bar_baz' * * snakeCase(['foo', 'bar', 'baz']) * // => 'foo_bar_baz' * ``` */ function snakeCase(value) { const _words = !Array.isArray(value) ? words(value) : value; return compose(_words); } exports.snakeCase = snakeCase; function compose(words) { return words.map((word) => word.toLowerCase()).join('_'); } exports.compose = compose;