How can you encode a string to Base64 in JavaScript?

前端 未结 26 3782
梦如初夏
梦如初夏 2020-11-21 04:02

I have a PHP script that can encode a PNG image to a Base64 string.

I\'d like to do the same thing using JavaScript. I know how to open files, but I\'m not sure how

26条回答
  •  借酒劲吻你
    2020-11-21 04:53

    To make a Base64 encoded String URL friendly, in JavaScript you could do something like this:

    // if this is your Base64 encoded string
    var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA=='; 
    
    // make URL friendly:
    str = str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
    
    // reverse to original encoding
    str = (str + '===').slice(0, str.length + (str.length % 4));
    str = str.replace(/-/g, '+').replace(/_/g, '/');
    

    See also this Fiddle: http://jsfiddle.net/magikMaker/7bjaT/

提交回复
热议问题