Monday, May 04, 2009

Escaping code symbols in blog postings

I wrote two bookmarklets to help escape code symbols in <textarea>s in blog postings (e.g., convert < to &lt; and so forth): Escape and Unescape.

I used a bookmarklet editor to create them, then dragged the editor generated links on to my bookmark bar. To use them, I highlight the appropriate part of a textarea and click Escape or Unescape on the bookmark bar.

Here's Escape:

javascript:
(function(){
var textareas=document.getElementsByTagName('textarea');
for(var i=textareas.length-1;i>=0;i--){
textarea=textareas[i];
var start=textarea.selectionStart;
var end=textarea.selectionEnd;
var prefix=textarea.value.substring(0,start);
var text=textarea.value.substring(start,end);
var suffix=textarea.value.substring(end,textarea.value.length);
text=text.replace(/&/g,'&amp;');
text=text.replace(/</g,'&lt;');
text=text.replace(/>/g,'&gt;');
text=text.replace(/"/g,'&quot;');
textarea.value=prefix+text+suffix;
}
}
)()

Here's Unescape:

javascript:
(function(){
var textareas=document.getElementsByTagName('textarea');
for(var i=textareas.length-1;i>=0;i--){
textarea=textareas[i];
var start=textarea.selectionStart;
var end=textarea.selectionEnd;
var prefix=textarea.value.substring(0,start);
var text=textarea.value.substring(start,end);
var suffix=textarea.value.substring(end,textarea.value.length);
text=text.replace(/&lt;/g,'<');
text=text.replace(/&gt;/g,'>');
text=text.replace(/&quot;/g,'"');
text=text.replace(/&amp;/g,'&');
textarea.value=prefix+text+suffix;
}
}
)()
To add these as links you need to perform the following substitutions:

s/ /%20/g;s/'/%27/g;s/"/%22/gs;s/&/%26/g;s/</%3c/g;s/>/%3e/g

By the way, if anyone knows how to identify in a bookmarklet which <textarea> in an HTML page has the focus, please let me know!

No comments: