export const stringUtils = { path: ['src', 'logic', 'utils'], file: { name: 'StringUtils', ext: 'ts', content: 'import BizSystemUtils from \'../utils/BizSystemUtils\';\n' + '\n' + '/**\n' + ' * 将字符串str中的s1全部替换为s2\n' + ' * @param str\n' + ' * @param s1\n' + ' * @param s2\n' + ' */\n' + 'function replaceAll(str: string, s1: string, s2: string): string {\n' + ' if (str.replaceAll) {\n' + ' return str.replaceAll(s1, s2);\n' + ' }\n' + ' // []在正则表达式中属于特殊字符,需要提前转义\n' + ' if (s1.indexOf(\'[\') > 0) {\n' + ' s1 = s1.replace(new RegExp(\'\\\\[\', \'gm\'), \'\\\\[\');\n' + ' }\n' + ' if (s1.indexOf(\']\') > 0) {\n' + ' s1 = s1.replace(new RegExp(\'\\\\]\', \'gm\'), \'\\\\]\');\n' + ' }\n' + ' if (s1.indexOf(\'(\') > 0) {\n' + ' s1 = s1.replace(new RegExp(\'\\\\(\', \'gm\'), \'\\\\(\');\n' + ' }\n' + ' if (s1.indexOf(\')\') > 0) {\n' + ' s1 = s1.replace(new RegExp(\'\\\\)\', \'gm\'), \'\\\\)\');\n' + ' }\n' + ' return str.replace(new RegExp(s1, \'gm\'), s2);\n' + '}\n' + '\n' + '/**\n' + ' * 返回字节数的显示字符串可以是Bytes/KB/MB/GB/TB,保留2位小数\n' + ' * @param bytes 字节数,数字\n' + ' * @returns 字节的显示字符串\n' + ' */\n' + 'function bytesToSizeString(bytes: number): string {\n' + ' const sizes = [\'Bytes\', \'KB\', \'MB\', \'GB\', \'TB\', \'PB\', \'EB\', \'ZB\', \'YB\'];\n' + ' if (BizSystemUtils.isNullValue(bytes) || bytes == 0) {\n' + ' return \'0 Byte\';\n' + ' }\n' + ' const i = Math.floor(Math.log(bytes) / Math.log(1024));\n' + ' let str = `${(bytes / Math.pow(1024, i)).toFixed(2)}`;\n' + ' if (str.endsWith(\'.00\')) {\n' + ' str = str.substr(0, str.length - 3);\n' + ' }\n' + ' return `${str} ${sizes[i]}`;\n' + '}\n' + '\n' + 'const StringUtils = {\n' + ' replaceAll,\n' + ' bytesToSizeString,\n' + '};\n' + 'export default StringUtils;\n', }, }; import BizSystemUtils from '../utils/BizSystemUtils'; /** * 将字符串str中的s1全部替换为s2 * @param str * @param s1 * @param s2 */ function replaceAll(str: string, s1: string, s2: string): string { if (str.replaceAll) { return str.replaceAll(s1, s2); } // []在正则表达式中属于特殊字符,需要提前转义 if (s1.indexOf('[') > 0) { s1 = s1.replace(new RegExp('\\[', 'gm'), '\\['); } if (s1.indexOf(']') > 0) { s1 = s1.replace(new RegExp('\\]', 'gm'), '\\]'); } if (s1.indexOf('(') > 0) { s1 = s1.replace(new RegExp('\\(', 'gm'), '\\('); } if (s1.indexOf(')') > 0) { s1 = s1.replace(new RegExp('\\)', 'gm'), '\\)'); } return str.replace(new RegExp(s1, 'gm'), s2); } /** * 返回字节数的显示字符串可以是Bytes/KB/MB/GB/TB,保留2位小数 * @param bytes 字节数,数字 * @returns 字节的显示字符串 */ function bytesToSizeString(bytes: number): string { const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; if (BizSystemUtils.isNullValue(bytes) || bytes == 0) { return '0 Byte'; } const i = Math.floor(Math.log(bytes) / Math.log(1024)); let str = `${(bytes / Math.pow(1024, i)).toFixed(2)}`; if (str.endsWith('.00')) { str = str.substr(0, str.length - 3); } return `${str} ${sizes[i]}`; } const StringUtils = { replaceAll, bytesToSizeString, }; export default StringUtils;