sentence-case.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var lowerCase = require('lower-case')
  2. var NON_WORD_REGEXP = require('./vendor/non-word-regexp')
  3. var CAMEL_CASE_REGEXP = require('./vendor/camel-case-regexp')
  4. var TRAILING_DIGIT_REGEXP = require('./vendor/trailing-digit-regexp')
  5. /**
  6. * Sentence case a string.
  7. *
  8. * @param {String} str
  9. * @param {String} locale
  10. * @param {String} replacement
  11. * @return {String}
  12. */
  13. module.exports = function (str, locale, replacement) {
  14. if (str == null) {
  15. return ''
  16. }
  17. replacement = replacement || ' '
  18. function replace (match, index, string) {
  19. if (index === 0 || index === (string.length - match.length)) {
  20. return ''
  21. }
  22. return replacement
  23. }
  24. str = String(str)
  25. // Support camel case ("camelCase" -> "camel Case").
  26. .replace(CAMEL_CASE_REGEXP, '$1 $2')
  27. // Support digit groups ("test2012" -> "test 2012").
  28. .replace(TRAILING_DIGIT_REGEXP, '$1 $2')
  29. // Remove all non-word characters and replace with a single space.
  30. .replace(NON_WORD_REGEXP, replace)
  31. // Lower case the entire string.
  32. return lowerCase(str, locale)
  33. }