to-title-case.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * To Title Case 2.1 – http://individed.com/code/to-title-case/
  3. * Copyright © 2008–2013 David Gouch. Licensed under the MIT License.
  4. *
  5. * modifications by @rvagg Apr-2014
  6. */
  7. //String.prototype.toTitleCase = function(){
  8. var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
  9. module.exports = function toTitleCase(str){
  10. return titleCase(str, smallWords)
  11. }
  12. module.exports.toTitleCase = module.exports
  13. var laxWords = require('./articles').concat(require('./prepositions')).concat(require('./conjunctions'))
  14. .concat(smallWords.source.replace(/(^\^\(|\)\$$)/g, '').split('|'))
  15. .concat(['is']) // a personal preference
  16. , laxWordsRe = new RegExp('^(' + laxWords.join('|') + ')$', 'i')
  17. module.exports.toLaxTitleCase = function toLaxTitleCase(str){
  18. return titleCase(str, laxWordsRe)
  19. }
  20. function titleCase (str, smallWords) {
  21. if (!str)
  22. return str
  23. return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function(match, index, title){
  24. if (index > 0 && index + match.length !== title.length &&
  25. match.search(smallWords) > -1 && title.charAt(index - 2) !== ':' &&
  26. (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
  27. title.charAt(index - 1).search(/[^\s-]/) < 0) {
  28. return match.toLowerCase();
  29. }
  30. if (match.substr(1).search(/[A-Z]|\../) > -1) {
  31. return match;
  32. }
  33. return match.charAt(0).toUpperCase() + match.substr(1);
  34. });
  35. }