Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

How to? base64-url

samintz

Scott Mintz
May
1,582
27
There is an encoding named base64-url that is almost identical to base64 encoding, except the characters / and + are replaced with _ and -.

Besides using 2 @replace functions, is there a simple way to do that?
 
This works. But is there a more elegant solution? Something akin to the translate() method in Python? Or a RE that could be used with @rereplace?
Code:
function b64encode-url=`%@replace[+,-,%@replace[/,_,%@b64encode[s,%$]]]`

echo %@b64encode-url[{"alg": "HS256", "typ": "JWT"}]
eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9
 
The sed command in Linux has a pretty nifty way of doing this:
Code:
sed 'y/+\//-_/'

echo tyh+VfuzIxCyGYDlkBA7DfyjrqmSHu6pQ2hoZuFqUSLPNY2N0mpHb3nk5K17HWP/3cYHBw7AhHale5wky6+sVA|wsl sed 'y/+\//-_/'
tyh-VfuzIxCyGYDlkBA7DfyjrqmSHu6pQ2hoZuFqUSLPNY2N0mpHb3nk5K17HWP_3cYHBw7AhHale5wky6-sVA
 
I wouldn't be surprised if tr were more efficient than sed.

Code:
v:\> echo a/b+c | tr "/+" "_-"
a_b-c
 
It seems to me that implementing it as a plugin function would be faster and more elegant than piling an external utility on top of @B64ENCODE. But I may be biased here....
 
Back
Top