How to? base64-url

samintz

Scott Mintz
May 20, 2008
1,574
27
Solon, OH, USA
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
 
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....