awesome-string
Version:
The ultimate JavaScript string library
30 lines (29 loc) • 852 B
JavaScript
import coerceToString from 'helper/string/coerce_to_string';
import lowerCase from 'case/lower_case';
import words from 'split/words';
/**
* Converts the `subject` to <a href="https://en.wikipedia.org/wiki/Snake_case">snake case</a>.
*
* @function snakeCase
* @static
* @since 1.0.0
* @memberOf Case
* @param {string} [subject=''] The string to convert to snake case.
* @return {string} Returns the snake case string.
* @example
* as.snakeCase('learning to fly');
* // => 'learning_to_fly'
*
* as.snakeCase('LearningToFly');
* // => 'learning_to_fly'
*
* as.snakeCase('-Learning-To-Fly-');
* // => 'learning_to_fly'
*/
export default function snakeCase(subject) {
const subjectString = coerceToString(subject);
if (subjectString === '') {
return '';
}
return words(subjectString).map(lowerCase).join('_');
}