var str = document.title; str = str.replace(/[[:punct:]]/g, '!'); alert(str);
Pretty simple. But that same script, in the form of a bookmarklet, looks like this:
In real life, that’s all on one line; I added a line break to make it fit better on screen. (The same goes for all subsequent bookmarklet examples in this article.) 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.2 You also need to escape non-ASCII characters, if any.
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 8.6 or TextWrangler 2.2. 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 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/Unix Support/Unix 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 works well for me, but it hasn’t exactly been widely tested. 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.
Worth noting: the
[:punct:] predefined character class works in Safari, but doesn’t seem to work in Mozilla-based browsers such as Firefox or Camino. So, you probably shouldn’t use that in production. ↩
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. ↩