words.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. var baseToString = require('../internal/baseToString'),
  2. isIterateeCall = require('../internal/isIterateeCall');
  3. /** Used to match words to create compound words. */
  4. var reWords = (function() {
  5. var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
  6. lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
  7. return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
  8. }());
  9. /**
  10. * Splits `string` into an array of its words.
  11. *
  12. * @static
  13. * @memberOf _
  14. * @category String
  15. * @param {string} [string=''] The string to inspect.
  16. * @param {RegExp|string} [pattern] The pattern to match words.
  17. * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
  18. * @returns {Array} Returns the words of `string`.
  19. * @example
  20. *
  21. * _.words('fred, barney, & pebbles');
  22. * // => ['fred', 'barney', 'pebbles']
  23. *
  24. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  25. * // => ['fred', 'barney', '&', 'pebbles']
  26. */
  27. function words(string, pattern, guard) {
  28. if (guard && isIterateeCall(string, pattern, guard)) {
  29. pattern = undefined;
  30. }
  31. string = baseToString(string);
  32. return string.match(pattern || reWords) || [];
  33. }
  34. module.exports = words;