From eca347cc4e029339c950f2c5a9583a721ef5c378 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=AB=E8=B0=B7=E5=89=91=E4=BB=99?= Date: Tue, 20 Jul 2021 20:53:57 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E4=B8=A4=E4=B8=AA=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- script-universal_function.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/script-universal_function.js b/script-universal_function.js index 04f1e42c..5b41b58c 100644 --- a/script-universal_function.js +++ b/script-universal_function.js @@ -45,6 +45,7 @@ function getQueryString(name, url) { return value; } + //数字补前导0 Number.prototype.prefixInteger = function(length, useGrouping = false) { return this.toLocaleString(undefined, { @@ -57,6 +58,28 @@ String.prototype.prefix = function(length = 2, prefix = '0') { let needAddLength = Math.max(length - this.length, 0); return new Array(needAddLength).fill(prefix).join('') + this; } + +// 将字符串转为Base64 +String.prototype.toBinary = function() { + const charCodes16Arr = [...this].map(char=>char.charCodeAt(0)); + const codeUnits = new Uint16Array(charCodes16Arr); + const charCodes = new Uint8Array(codeUnits.buffer); + const result = [...charCodes].map(code=>String.fromCharCode(code)).join(''); + return result; +} +String.prototype.toBase64 = function() { + return btoa(this.toBinary()); +} +String.fromBinary = function(binary) { + const bytes = new Uint8Array([...binary].map(char=>char.charCodeAt(0))); + const charCodes = new Uint16Array(bytes.buffer); + const result = [...charCodes].map(code=>String.fromCharCode(code)).join(''); + return result; +} +String.fromBase64 = function(base64) { + return String.fromBinary(atob(base64)); +} + //大数字缩短长度,默认返回本地定义字符串 Number.prototype.bigNumberToString = function() { return this.toLocaleString();