Is there a native JS method for converting `+` and `/` to `-` and `_` prior to base64url encoding? What is it?

151 Views Asked by At

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?

1

There are 1 best solutions below

1
On

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

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

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