tools/utils/src/modules/string-string.js

  1. /**
  2. * @module @svizzle/utils/string-string
  3. */
  4. import * as _ from 'lamb';
  5. import {sliceString} from './string_proto-string.js';
  6. import {endsWithNewLine} from './string-boolean.js';
  7. import {getEndOfLineLength} from './string-number.js';
  8. /**
  9. * Capitalise the input string
  10. *
  11. * @function
  12. * @arg {string}
  13. * @return {string}
  14. *
  15. * @example
  16. > capitalize('hello')
  17. 'Hello'
  18. *
  19. * @since 0.8.0
  20. */
  21. export const capitalize = s => s.charAt(0).toUpperCase() + s.slice(1);
  22. /**
  23. * Decapitalise the input string (makes the first letter lowercase)
  24. *
  25. * @function
  26. * @arg {string}
  27. * @return {string}
  28. *
  29. * @example
  30. > decapitalize('Hello')
  31. 'hello'
  32. > decapitalize('HELLO')
  33. 'hELLO'
  34. *
  35. * @since 0.20.0
  36. */
  37. export const decapitalize = s => s.charAt(0).toLowerCase() + s.slice(1);
  38. /**
  39. * Trim the last char of the provided string if it's a newline
  40. *
  41. * @function
  42. * @arg {string} string
  43. * @return {array}
  44. *
  45. * @example
  46. > trimLastNewline('a\nb\nc')
  47. 'a\nb\nc'
  48. > trimLastNewline('a\nb\nc\n')
  49. 'a\nb\nc'
  50. > trimLastNewline('a\nb\nc\n\n')
  51. 'a\nb\nc\n'
  52. > trimLastNewline('a\nb\nc\r\n')
  53. 'a\nb\nc'
  54. > trimLastNewline('a\nb\nc\n\r\n')
  55. 'a\nb\nc\n'
  56. *
  57. * @since 0.5.0
  58. */
  59. export const trimLastNewline =
  60. _.when(endsWithNewLine, s => {
  61. const L = getEndOfLineLength(s);
  62. return sliceString(s, 0, -L);
  63. });