-1

I'm reading through a codebase and noticed the author manually uses replace to sanitize a string prior to base64url encoding, as per the base64url specification.

str = str.replace(/=+$/, ''); // remove padding equal characters
str = str.replace(/\+/g, '-'); // replace characters according to base64url specifications
str = str.replace(/\//g, '_'); // replace characters according to base64url specifications

Is there a native method for doing this? What is it?

neaumusic
  • 10,027
  • 9
  • 55
  • 83
  • @alfasin apparently this has to do with JWT specifically -- using base64url rather than base64, and I noticed JavaScript also doesn't have a native sha256 hashing algorithm, so I'm thinking it's possible W3C doesn't intend for JS to run on the server? – neaumusic Nov 07 '18 at 18:28
  • 1
    Look what googling `base64url javascript` found: https://www.npmjs.com/package/base64url – Adam Jenkins Nov 07 '18 at 18:36
  • @Adam Look at the package domain `npmjs.com` – neaumusic Nov 07 '18 at 18:42

1 Answers1

0

Yes. In javascript there's encodeURIComponent() and decodeURIComponent():

https://www.w3schools.com/tags/ref_urlencode.asp

https://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

schlock
  • 519
  • 3
  • 5
  • 14
  • That was my first instinct, and I'm thinking there should be a similar method for converting with this specific JWT base64url ruleset (not including `%` etc). JWT is relatively new, so I'm thinking it's just not standardized by W3C, but eventually it might be – neaumusic Nov 07 '18 at 18:50