JavaScript中是否有任何方法可以用来编码和解码使用base64编码的字符串?


当前回答

在Node.js中,我们可以用简单的方式做到这一点

var base64 = 'SGVsbG8gV29ybGQ='
var base64_decode = new Buffer(base64, 'base64').toString('ascii');

console.log(base64_decode); // "Hello World"

其他回答

在基于Gecko/ webkit的浏览器(Firefox、Chrome和Safari)和Opera中,可以使用btoa()和atob()。

原来的答案:如何在JavaScript中将字符串编码为Base64 ?

以下是Sniper的文章的压缩版。它假定格式良好的base64字符串,没有回车。这个版本消除了几个循环,从Yaroslav中添加了&0xff修复,消除了尾随null,再加上一些代码golf。

decodeBase64 = function(s) {
    var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
    var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for(i=0;i<64;i++){e[A.charAt(i)]=i;}
    for(x=0;x<L;x++){
        c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
        while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
    }
    return r;
};

现代浏览器有内置的javascript函数用于Base64编码btoa()和解码atob()。有关旧版本浏览器支持的更多信息:https://caniuse.com/?search=atob

但是,请注意atob和btoa函数仅适用于ASCII字符集。 如果你需要Base64函数的UTF-8字符集,你可以这样做:

function base64_encode(s) {      
    return btoa(unescape(encodeURIComponent(s)));
}
function base64_decode(s) {      
    return decodeURIComponent(escape(atob(s)));
}

PHP .js项目有很多PHP函数的JavaScript实现。包括Base64_encode和base64_decode。

不管怎样,我从其他答案中得到了启发,写了一个小实用程序,调用特定于平台的api,从Node.js或浏览器中普遍使用:

/** * Encode a string of text as base64 * * @param data The string of text. * @returns The base64 encoded string. */ function encodeBase64(data: string) { if (typeof btoa === "function") { return btoa(data); } else if (typeof Buffer === "function") { return Buffer.from(data, "utf-8").toString("base64"); } else { throw new Error("Failed to determine the platform specific encoder"); } } /** * Decode a string of base64 as text * * @param data The string of base64 encoded text * @returns The decoded text. */ function decodeBase64(data: string) { if (typeof atob === "function") { return atob(data); } else if (typeof Buffer === "function") { return Buffer.from(data, "base64").toString("utf-8"); } else { throw new Error("Failed to determine the platform specific decoder"); } }