path.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * 获取文件名
  3. * @example filename("a/b/c.txt") // "c"
  4. */
  5. export function filename(path: string): string {
  6. return basename(path.substring(0, path.lastIndexOf(".")));
  7. }
  8. /**
  9. * 获取路径的最后一部分
  10. * @example basename("a/b/c.txt") // "c.txt"
  11. */
  12. export function basename(path: string): string {
  13. let index = path.lastIndexOf("/");
  14. index = index > -1 ? index : path.lastIndexOf("\\");
  15. if (index < 0) {
  16. return path;
  17. }
  18. return path.substring(index + 1);
  19. }
  20. /**
  21. * 获取文件扩展名
  22. * @example extname("a/b/c.txt") // "txt"
  23. */
  24. export function extname(path: string): string {
  25. let index = path.lastIndexOf(".");
  26. if (index < 0) {
  27. return "";
  28. }
  29. return path.substring(index + 1);
  30. }
  31. /**
  32. * 首字母大写
  33. * @example firstUpperCase("useInfo") // "UseInfo"
  34. */
  35. export function firstUpperCase(value: string): string {
  36. return value.charAt(0).toLocaleUpperCase() + value.slice(1);
  37. }
  38. /**
  39. * 获取地址栏参数
  40. * @example getUrlParam("a") // "1"
  41. */
  42. export function getUrlParam(name: string): string | null {
  43. // #ifdef H5
  44. const params = new URLSearchParams(window.location.search);
  45. const value = params.get(name);
  46. return value !== null ? decodeURIComponent(value) : null;
  47. // #endif
  48. }
  49. /**
  50. * 连接路径
  51. * @example pathJoin("https://www.baidu.com/", "/a/b/c.txt") // "https://www.baidu.com/a/b/c.txt"
  52. */
  53. export function pathJoin(...parts: string[]): string {
  54. return parts.map((part) => part.replace(/(^\/+|\/+$)/g, "")).join("/");
  55. }