做了很多项目,发现有很多公用的js方法可以总结出来,不同的项目却可以使用这些通用的方法去解决业务上面的问题;
时间常用方法和冷门方法
请参考timeUtil
获取去当前网址url
export function GetCurrentProjectUrl(pathname: string) {const location = window.location;return location.protocol + location.hostname + (location.port ? ':' + location.port : '') + '/#/' + pathname;
}
获取base URL
export function GetBaseURL(url) {return url.replace(/[?#].*$/, '')
}
URL参数转换为对象
export function GetURLParameters (url) {return url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( (a, v) => ( (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a ), {};
}
检查一个元素是否包含另一个元素
export function elementContains (parent, child) { parent !== child && parent.contains(child);
}
格式化文件大小
export function FormatFileSize(size: number): string{if (size < 1024) {return size + 'B';} else if (size < 1024 * 1024) {return (size / 1024).toFixed(2) + 'KB';} else if (size < 1024 * 1024 * 1024) {return (size / (1024 * 1024)).toFixed(2) + 'MB';} else {return (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB';}
}
url转blob
export function UrlToBlob(url: string) {return new Promise((resolve, reject) => {const xhr: any = new XMLHttpRequest();xhr.open('GET', url, true);xhr.responseType = 'blob';xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { resolve(xhr.response);} else {// 错误处理reject(xhr.statusText);};};};xhr.send();});
};
url转blob-拓展文件下载
import SaveAS from 'file-saver';
export function HandleUrlDownloadFile(filename: string, url: string){return new Promise((resolve, reject) => {UrlToBlob(url).then((blob: any) => {SaveAS(blob, filename || '下载文件');resolve(filename);}).catch(() => {AzMessages('error', '下载失败')reject();});})
};
base64toFile
export function Base64ToFile (dataurl: string, filename='截图') {let arr: any = dataurl.split(',');let mime = arr[0].match(/:(.*?);/)[1];let suffix = mime.split('/')[1];let bstr = atob(arr[1]);let n = bstr.length;let u8arr = new Uint8Array(n);while (n--) {u8arr[n] = bstr.charCodeAt(n);}return new File([u8arr], `${filename}.${suffix}`, {type: mime});
};
对象拷贝-lodash库
export function CloneDeep(obj: any) {return _.cloneDeep(obj);
};
判读网络情况
export function HandleNetworkSituation () { // 判断网络情况if (window.navigator.onLine === true) {return true} else {return false}
}
浮点数如果是整数返回整数否则返回浮点数
/* 这个方法比较冷门,有点贴业务了,之前做数据大屏的时候后台返回18.00, 18.12;图表显示的话,整数就显示18,所以写了个方法,说不定做大屏展示的同学会用到
*/
export function FloatPointToInteger (code: number): number {if (typeof code === 'number' && code % 1 === 0) {code = Math.ceil(code)}return code
}
数字转中文
export function convertToChinaNum(num) { // 数字下标变中文var arr1 = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']var arr2 = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿']if (!num || isNaN(num)) {return '零'}var english = num.toString().split('')var result = ''for (var i = 0; i < english.length; i++) {// 倒序排列设值var des_i = english.length - 1 - iresult = arr2[i] + resultvar arr1_index = english[des_i]result = arr1[arr1_index] + result}// 将【零千、零百】换成【零】 【十零】换成【十】result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十')// 合并中间多个零为一个零result = result.replace(/零+/g, '零')// 将【零亿】换成【亿】【零万】换成【万】result = result.replace(/零亿/g, '亿').replace(/零万/g, '万')// 将【亿万】换成【亿】result = result.replace(/亿万/g, '亿')// 移除末尾的零result = result.replace(/零+$/, '')// 将【零一十】换成【零十】// result = result.replace(/零一十/g, '零十');// 貌似正规读法是零一十// 将【一十】换成【十】result = result.replace(/^一十/g, '十')return result
}
获取选定的文本
export function getSelectedText () {return window.getSelection().toString();
}
文本复制到剪贴板
export function copyToClipboard (str) { if (navigator && navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(str) return Promise.reject('The Clipboard API is not available.')
}
export function CopyToClipboard(text: string) { return new Promise((resolve, reject) => { if (window.navigator.clipboard) { // 推荐方法,支持最新浏览器 navigator.clipboard.writeText(text).then(resolve, reject); } else { // 兼容不支持navigator.clipboard的浏览器 var textArea = document.createElement("textarea"); textArea.value = text; document.body.appendChild(textArea); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; resolve(successful); } catch (err) { reject(err); } finally { document.body.removeChild(textArea); } } });
}