How to easily perform URL encoding in AppleScript?

Hi all,

I need for perform URL encoding on the input text string in AppleScript. After some searching, I was surprised to find out this was not as trivial as I thought. Shortcuts really spoiled me with those built-in Actions :sweat_smile:

I did find this dated StackOverflow thread but it didnā€™t work for me, perhaps because the thread was using bash while Iā€™m using zsh?

My arsenal is limited to AppleScript (and by extension, do shell script) because the encoding is part of a DEVONthink Smart Rule Iā€™m building. Any help is greatly appreciated.

You can override your default shell either by specifying the shell in the ā€œdoā€, r by using a shebang in an external script called from the ā€œdoā€.

Thanks, I had no idea this was possible!
I just installed bash to test the idea from the StackOverflow thread (using the open command to perform URL encoding) but all my attempts ended in failure. I guess Iā€™m doing something wrong here.

I come from graphic automation tools such as Shortcuts and started writing scripts very recently. Are there any ready-made command line utilities specifically made for URL encode and decode? I found some for Linux but seemingly none for macOS.

To the extent that open parses URLs, itā€™s done internally. It doesnā€™t return an encoded URL that you can use later in your script. This is unrelated to the shell youā€™re using.

There are different ways to encode URLs, so we have to know what DevonTHINK needs. For example, do slashes and colons have to be encoded?

Also, are you sure need to do any encoding at all? The URLs you get from copying the field at the top of the browser and from right-clicking and copying links from the body of a web page are already encoded.

Thanks for the explanation, I suspected so.

I havenā€™t considered this and tbh I donā€™t know its detailed needs. But fwiw, the input strings are titles of notes, so most if not all the non-alphanumerical characters are spaces and commonly used punctuations.

I do need to encode, because as noted above, Iā€™m encoding note titles.

This Stack Overflow thread you list has several options including non-Bash based solutions.

There are also some ohmyzsh plugins to give you encode and decode.

Thank you for providing many options! I was experimenting with this npm package just now. Iā€™ll see if thereā€™re better options since this one depends on Node.js.