Remove trailing “=” when base64 encoding

前端 未结 9 2049
时光取名叫无心
时光取名叫无心 2020-11-29 23:58

I am noticing that whenever I base64 encode a string, a \"=\" is appended at the end. Can I remove this character and then reliably decode it later by adding it back, or is

9条回答
  •  囚心锁ツ
    2020-11-30 00:25

    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
    if (str.length % 4 != 0){
      str += ('===').slice(0, 4 - (str.length % 4));
    }
    str = str.replace(/-/g, '+').replace(/_/g, '/');
    

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

提交回复
热议问题