swisspig.net - To hell with the pig... I'm going to Switzerland.

Converting Ampersands Bookmarklet (Saturday, October 8, 2005)

Well, as some of you may know, I recently made an effort to make the largest part of my site XHTML 1.0 (Transitional) compliant. And while I was successful for for the main pages, I hadn't bothered to go back through my archives. So I did that the other day, and as far as I can tell, every page on the site is compliant. One thing I found irksome though, was the need to convert ampersands into &, even in URLs! So after a little effort, I came up with a sed script to do it:

$ sed 's/&/\&/g;s/&\([a-zA-Z]\+;\)/\&\1/g'

But that wasn't terribly convenient, as I need to be able to do it while I'm editing, so I decided to figure out vim's cool filtering capability (which I've always known about, but never bothered to really understand), and combine it with the ability to map commands to keys:

map <F6> :1,$!sed 's/&/\&amp;/g;s/&amp;\([a-zA-Z]\+;\)/\&\1/g'<CR>

Finally, I realize that most people don't use vi to edit their blog entries, but rather use evil cumbersome browser UIs. So, I wrote a little JavaScript bookmarklet to convert ampersands in any text area with the click of a button. All you have to do is bookmark the link below, or create a bookmark from the code here (don't forget to remove the spaces from the line breaks):

javascript:for(i=0;i<document.forms.length;i++){for(j=0;j<
document.forms[i].elements.length;j++){if(document.forms[i
].elements[j].type=='textarea'){void(document.forms[i].ele
ments[j].value=document.forms[i].elements[j].value.replace
(new RegExp('&','g'),'&amp;'));void(document.forms[i].elem
ents[j].value=document.forms[i].elements[j].value.replace(
new RegExp('&amp;\([a-zA-Z]\+;\)','g'),'&$1'));}}}

Try it!

The only catch, is that if you want to actually display the text &amp;, you have to specifically encode the ampersand as &amp;amp;, because the script knows not to convert ampersands that are already part of an ampersand entity. I know it sounds complicated, but trust me.

Oh yeah, and I have no idea if this works in Internet Explorer. IE is its own punishment. If you want to use this script, do yourself a favor and download Firefox... or do yourself more of a favor, get yourself some shell access, and use vi! Okay, that's probably too much for all but the most hardcore geeks.

—Brian (10/8/2005 11:18 PM)
(0 comments)

Comments

No comments.

Name
URL
Comment
(no html)
 

Disclaimer: Opinions on this site are those of Brian Ziman and do not necessarily
reflect the views of any other organizations or businesses mentioned.