1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | 'use strict'
|
11 |
|
12 | const lowercase = require('./lowercase')
|
13 | const uppercase = require('./uppercase')
|
14 |
|
15 | const JOINER = '_'
|
16 |
|
17 | const 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 |
|
30 | function 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 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 | snakecase.isSnakecase = function (str) {
|
52 | return str && /^[a-z_]+$/.test(str)
|
53 | }
|
54 |
|
55 | module.exports = snakecase
|