kebabCase.js 1.9 KB

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