You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

toTitleCase.js 1001B

1234567891011121314151617181920212223242526272829303132333435
  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. * https://github.com/gouch/to-title-case
  5. */
  6. import trim from './trim';
  7. const smallWords =
  8. /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
  9. // test
  10. export default function toTitleCase(string) {
  11. return trim(string).replace(
  12. /[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g,
  13. (match, index, title) => {
  14. if (
  15. index > 0 &&
  16. index + match.length !== title.length &&
  17. match.search(smallWords) > -1 &&
  18. title.charAt(index - 2) !== ':' &&
  19. (title.charAt(index + match.length) !== '-' ||
  20. title.charAt(index - 1) === '-') &&
  21. title.charAt(index - 1).search(/[^\s-]/) < 0
  22. ) {
  23. return match.toLowerCase();
  24. }
  25. if (match.substr(1).search(/[A-Z]|\../) > -1) {
  26. return match;
  27. }
  28. return match.charAt(0).toUpperCase() + match.substr(1);
  29. }
  30. );
  31. }