string.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. const reLine = /^/mg
  7. export function indentString(str: string, count: number, indent: string) {
  8. return count === 0 ? str : str.replace(reLine, indent.repeat(count))
  9. }
  10. /** Add space between camelCase text. */
  11. export function splitCamelCase(str: string) {
  12. return str.replace(/([a-z\xE0-\xFF])([A-Z\xC0\xDF])/g, '$1 $2')
  13. }
  14. /** Split camelCase text and capitalize. */
  15. export function camelCaseToWords(str: string) {
  16. return capitalize(splitCamelCase(str))
  17. }
  18. export const lowerCase = (str: string) => str.toLowerCase()
  19. export const upperCase = (str: string) => str.toUpperCase()
  20. /** Uppercase the first character of each word. */
  21. export function capitalize(str: string) {
  22. return str.toLowerCase().replace(/^\w|\s\w/g, upperCase);
  23. }
  24. export function splitSnakeCase(str: string) {
  25. return str.replace(/_/g, ' ')
  26. }
  27. export function snakeCaseToWords(str: string) {
  28. return capitalize(splitSnakeCase(str))
  29. }
  30. export function stringToWords(str: string) {
  31. return capitalize(splitCamelCase(splitSnakeCase(str)))
  32. }
  33. export function substringStartsWith(str: string, start: number, end: number, target: string) {
  34. let len = target.length;
  35. if (len > end - start) return false;
  36. for (let i = 0; i < len; i++) {
  37. if (str.charCodeAt(start + i) !== target.charCodeAt(i)) return false;
  38. }
  39. return true;
  40. }