UNPKG

1.74 kBJavaScriptView Raw
1var toValueString = require('./toValueString')
2var helperStringSubstring = require('./helperStringSubstring')
3var helperStringUpperCase = require('./helperStringUpperCase')
4var helperStringLowerCase = require('./helperStringLowerCase')
5
6var camelCacheMaps = {}
7
8/**
9 * 将带字符串转成驼峰字符串,例如: project-name 转为 projectName
10 *
11 * @param {String} str 字符串
12 * @return {String}
13 */
14function camelCase (str) {
15 str = toValueString(str)
16 if (camelCacheMaps[str]) {
17 return camelCacheMaps[str]
18 }
19 var strLen = str.length
20 var rest = str.replace(/([-]+)/g, function (text, flag, index) {
21 return index && index + flag.length < strLen ? '-' : ''
22 })
23 strLen = rest.length
24 rest = rest.replace(/([A-Z]+)/g, function (text, upper, index) {
25 var upperLen = upper.length
26 upper = helperStringLowerCase(upper)
27 if (index) {
28 if (upperLen > 2 && index + upperLen < strLen) {
29 return helperStringUpperCase(helperStringSubstring(upper, 0, 1)) + helperStringSubstring(upper, 1, upperLen - 1) + helperStringUpperCase(helperStringSubstring(upper, upperLen - 1, upperLen))
30 }
31 return helperStringUpperCase(helperStringSubstring(upper, 0, 1)) + helperStringSubstring(upper, 1, upperLen)
32 } else {
33 if (upperLen > 1 && index + upperLen < strLen) {
34 return helperStringSubstring(upper, 0, upperLen - 1) + helperStringUpperCase(helperStringSubstring(upper, upperLen - 1, upperLen))
35 }
36 }
37 return upper
38 }).replace(/(-[a-zA-Z])/g, function (text, upper) {
39 return helperStringUpperCase(helperStringSubstring(upper, 1, upper.length))
40 })
41 camelCacheMaps[str] = rest
42 return rest
43}
44
45module.exports = camelCase