/** * Base64 编解码工具(底层基础工具) */ /** * Base64编码 * @param str 要编码的字符串 * @returns 编码后的Base64字符串 */ export function encode(str: string): string { return btoa(encodeURIComponent(str)) } /** * Base64解码 * @param base64 要解码的Base64字符串 * @returns 解码后的原始字符串 */ export function decode(base64: string): string { return decodeURIComponent(atob(base64)) } /** * URL安全的Base64编码 * @param str 要编码的字符串 * @returns 编码后的Base64字符串 */ export function encodeURLSafe(str: string): string { return encode(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') } /** * URL安全的Base64解码 * @param base64 要解码的Base64字符串 * @returns 解码后的原始字符串 */ export function decodeURLSafe(base64: string): string { let str = base64.replace(/-/g, '+').replace(/_/g, '/') // 补齐等号 while (str.length % 4) { str += '=' } return decode(str) }