Automating encoding strings with Alfred Workflows
Following on from the guide mentioned above one of the other things I have to do regularly is encode strings. This is another task that can be easily automated with Alfred workflows.
So I created a workflow that can encode strings in either URL encoding or Base64 encoding.
This workflow allows me to quickly encode any string using either method, making it a valuable tool in my productivity arsenal. However whilst it doesn’t look much different to the UUID and key generation workflows, it is actually a little more complex as we need to pass the string to be encoded as an argument to the workflow and we want to get that string in different ways.
The string input methods
Section titled “The string input methods”With this workflow we have three different ways of providing the string to be encoded:
- Clipboard: The simplest method is to copy the text you want to encode to the clipboard and then trigger the workflow. This is useful for quick encodings without needing to type anything.
- Argument: You can also pass the string to be encoded as an argument when triggering the workflow. This is useful for more complex strings or when you want to encode a specific piece of text.
- Selection: Finally, you can select text in any application and then trigger the workflow. Alfred will use the selected text as the input for encoding. This is a powerful feature that allows for quick encoding of text without needing to copy or type it manually. This is achieved using Alfred’s Universal Actions.
The encoding methods
Section titled “The encoding methods”With this workflow, you can choose between two encoding methods:
- URL Encoding: This method encodes the string so that it can be safely transmitted over the internet. It replaces unsafe ASCII characters with a ”%” followed by two hexadecimal digits. This is useful for encoding query parameters in URLs.
- Base64 Encoding: This method encodes binary data into a text string using a base64 representation. However it can also be used for encoding any string which is where this workflow comes in handy.
The script blocks for each encoding method are as follows:
URL Encoding:
#!/bin/zshTEXT="$1"
# If no text is passed, use the clipboardif [ -z "$TEXT" ]; then TEXT=$(pbpaste)fi
/usr/bin/osascript -l JavaScript -e "encodeURIComponent('$TEXT')"
Base64 Encoding:
#!/bin/zshTEXT="$1"
# If no text is passed, use the clipboardif [ -z "$TEXT" ]; then TEXT=$(pbpaste)fi
echo -n "$TEXT" | base64