tools.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* eslint-disable import/prefer-default-export */
  2. export const replaceAll = (FindText: RegExp | string, RepText: string, str: string): string => {
  3. const regExp = new RegExp(FindText, 'g');
  4. return str.replace(regExp, RepText);
  5. };
  6. // 全局替换 字符串(处理字符串内有需要转义的字符 如:'()')
  7. export const replaceStrAll = (replaceThis: string, withThis: string, inThis: string): string => {
  8. withThis = withThis.replace(/\$/g, '$$$$');
  9. return inThis.replace(
  10. // eslint-disable-next-line no-useless-escape
  11. new RegExp(replaceThis.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|<>\-\&])/g, '\\$&'), 'g'),
  12. withThis
  13. );
  14. };
  15. // 是否未定义
  16. export const isDef = (value: any): boolean => {
  17. return value !== undefined && value !== null;
  18. };
  19. // 是否为空值
  20. export const isEmptyVal = (val: any): boolean => {
  21. return val === null || val === undefined || val === '';
  22. };
  23. export const getPatten = (decimal: number) => {
  24. const header = '0,0.';
  25. return header + '00000000'.substr(0, decimal);
  26. };
  27. // 判断是否数字
  28. export const isNumeric = (n: any) => {
  29. /* eslint-disable */
  30. var t = typeof n;
  31. return t == 'number'
  32. ? !isNaN(n) && isFinite(n)
  33. : t == 'string'
  34. ? !n.length
  35. ? false
  36. : n.length == 1
  37. ? /\d/.test(n)
  38. : /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n)
  39. : t == 'object'
  40. ? !!n && typeof n.valueOf() == 'number' && !(n instanceof Date)
  41. : false;
  42. };
  43. // 判断数据库中的某个字段是否为空
  44. export const isEmptyForDB = (obj: any) => {
  45. return obj == null || obj === -1 || obj === '';
  46. };
  47. // 判断是否过期
  48. export const isExpired = (deadline:number)=> {
  49. // deadline 为 0 表示无限制
  50. if (deadline !== 0) {
  51. return Date.now() >= deadline + 24 * 60 * 60 * 1000;
  52. }
  53. return false;
  54. }
  55. const canvas = document.createElement("canvas");
  56. export const getTextWidth = (text:string, font :string)=> {
  57. const context = canvas.getContext("2d") as CanvasRenderingContext2D;
  58. context.font = font;
  59. const metrics = context.measureText(text);
  60. return metrics.width;
  61. }