string-utils.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * @fileoverview Utilities to operate on strings.
  3. * @author Stephen Wade
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Helpers
  8. //------------------------------------------------------------------------------
  9. // eslint-disable-next-line no-control-regex -- intentionally including control characters
  10. const ASCII_REGEX = /^[\u0000-\u007f]*$/u;
  11. /** @type {Intl.Segmenter | undefined} */
  12. let segmenter;
  13. //------------------------------------------------------------------------------
  14. // Public Interface
  15. //------------------------------------------------------------------------------
  16. /**
  17. * Converts the first letter of a string to uppercase.
  18. * @param {string} string The string to operate on
  19. * @returns {string} The converted string
  20. */
  21. function upperCaseFirst(string) {
  22. if (string.length <= 1) {
  23. return string.toUpperCase();
  24. }
  25. return string[0].toUpperCase() + string.slice(1);
  26. }
  27. /**
  28. * Counts graphemes in a given string.
  29. * @param {string} value A string to count graphemes.
  30. * @returns {number} The number of graphemes in `value`.
  31. */
  32. function getGraphemeCount(value) {
  33. if (ASCII_REGEX.test(value)) {
  34. return value.length;
  35. }
  36. segmenter ??= new Intl.Segmenter("en-US"); // en-US locale should be supported everywhere
  37. let graphemeCount = 0;
  38. // eslint-disable-next-line no-unused-vars -- for-of needs a variable
  39. for (const unused of segmenter.segment(value)) {
  40. graphemeCount++;
  41. }
  42. return graphemeCount;
  43. }
  44. module.exports = {
  45. upperCaseFirst,
  46. getGraphemeCount
  47. };