string_utils.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. export const readableDate = (s: string) => {
  2. const ts = new Date(s);
  3. const date = ts.toLocaleDateString();
  4. const time = ts.toLocaleTimeString([], {
  5. hour: "numeric",
  6. minute: "2-digit",
  7. });
  8. return `${time} on ${date}`;
  9. };
  10. export const capitalize = (s: string) => {
  11. return s.charAt(0).toUpperCase() + s.substring(1).toLowerCase();
  12. };
  13. const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
  14. export const dotenv_parse = (src: string): Record<string, string> => {
  15. // Parser src into an Object
  16. const obj = {} as Record<string, string>;
  17. // Convert buffer to string
  18. let lines = src.toString();
  19. // Convert line breaks to same format
  20. lines = lines.replace(/\r\n?/gm, "\n");
  21. let match;
  22. while ((match = LINE.exec(lines)) != null) {
  23. const key = match[1];
  24. // Default undefined or null to empty string
  25. let value = match[2] || "";
  26. // Remove whitespace
  27. value = value.trim();
  28. // Check if double quoted
  29. const maybeQuote = value[0];
  30. // Remove surrounding quotes
  31. value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
  32. // Expand newlines if double quoted
  33. if (maybeQuote === '"') {
  34. value = value.replace(/\\n/g, "\n");
  35. value = value.replace(/\\r/g, "\r");
  36. }
  37. // Add to object
  38. obj[key] = value;
  39. }
  40. return obj;
  41. };