UNPKG

1.3 kBJavaScriptView Raw
1/**
2 * Convert string into snake case.
3 * Join punctuation with underscore.
4 * @memberof module:stringcase/lib
5 * @function snakecase
6 * @param {string} str - String to convert.
7 * @returns {string} Snake cased string.
8 */
9
10'use strict'
11
12const lowercase = require('./lowercase')
13const uppercase = require('./uppercase')
14
15const JOINER = '_'
16
17const replacing = {
18 from: /([A-Z]+)/g,
19 to (match, $1, offset) {
20 let prefix = offset === 0 ? '' : JOINER
21 let len = $1.length
22 let replaced = len === 1 ? lowercase($1) : (
23 lowercase($1.substr(0, len - 1)) + JOINER + lowercase($1[ len - 1 ])
24 )
25 return prefix + replaced
26 }
27}
28
29/** @lends snakecase */
30function snakecase (str) {
31 if (snakecase.isSnakecase(str)) {
32 return str
33 }
34 str = String(str).replace(/[\-\.\s]/g, JOINER)
35 if (!str) {
36 return str
37 }
38 if (uppercase.isUppercase(str)) {
39 str = lowercase(str)
40 }
41 return str.replace(replacing.from, replacing.to).replace(/_+/g, '_')
42}
43
44/**
45 * Checks whether the string are snakecase.
46 * @memberof module:stringcase/lib
47 * @function snakecase.isSnakecase
48 * @param {string} str - String to check.
49 * @returns {boolean} - True if the string are snakecase.
50 */
51snakecase.isSnakecase = function (str) {
52 return str && /^[a-z_]+$/.test(str)
53}
54
55module.exports = snakecase