camelCase.js 1.7 KB

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