-1

I'm using this function for base64 decode/encode URL in javascript but i've seen many gives notice about making Base64 encoded String URL friendly and to use

// 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, '/');

jsfiddle

I see it only replce + with - and \ with _ so what is the point! i mean why should i?

Reham Fahmy
  • 1,058
  • 1
  • 7
  • 10

1 Answers1

0

If you would not replace the characters they could get misinterpreted, like pointed out in this answer. This would result in either displaying wrong content or more likely displaying nothing.

For explanation:
In URLs the follwing characters are reserved: : / ? # [ ] @ : $ & ' ( ) * + , ; =

Like pointed out in this answer you need 65 characters to encode data, but the sum of uppercase-, lowercase characters and digits is only 62. So it needs three additional characters which are + = /. These three are reserved. So you need to replace them. As of right now I am not entirely sure about -.

Community
  • 1
  • 1
frncsdrk
  • 487
  • 5
  • 12