By John Gruber
Black hole takes your money.
MailChimp makes you money.
[Update 27 January 2014: I’ve fixed a small bug in the below script. I’m also now hosting a copy of it on Gist.]
var str = document.title; alert(str.toUpperCase() + "!");
Pretty simple. But that same script, in the form of a bookmarklet, looks like this (all on one line):
In addition to removing line breaks, spaces need to be escaped (
%20), and it’s a good idea to escape single- and double-quotes, too.1 You also need to escape non-ASCII characters.
var str = document.title; alert(str);
My “Make Bookmarklet” script will return:
If you run it again, with a comment on the first line that begins with “
And, as an added bonus, the bookmarklet URL string is also placed on the clipboard, which means you can run the script, and then immediately switch to your browser and paste it into the browser’s bookmarks editor.
Here’s how to use it with BBEdit or TextWrangler. If you use some other editor, there’s probably some easy way to use shell script filters with your editor, too — there’s nothing BBEdit-specific in this script. (It ought to work as a service via Automator or ThisService, too, but I haven’t tried that.)
Copy the above Perl script and paste it into a new text window.
Save it in your ~/Library/Application Support/BBEdit/Text Filters/ folder. (Substitute “TextWrangler” for “BBEdit” if necessary.) I named mine “Make Bookmarklet”, but you can name it whatever you want.
When run in a document window with a range of selected text, the selection will be passed as input and replaced with the output. If no text is selected, the entire contents of the window will be used as input and replaced with the output. With this script, it’s generally easiest to run it with no selection.
This script has worked well for me and many others since I first published it in 2007. But if it eats your source code, Undo is your friend. If you spot anything wrong or wish to suggest improvements, please do let me know, or fork it on Gist.
It’s unclear to me what characters must be escaped in a bookmarklet URL. Some sources suggest that other punctuation characters, such as brackets and semicolons, ought to be escaped, too, but I can see no practical reason to do so. If you want to be really conservative and escape just about everything, change this line:
uri_escape_utf8($bookmarklet, qq(%'" \x00-\x1f\x7f-\xff));
Personally, I prefer to keep the bookmarklet URL itself as readable as possible. ↩︎