replace selected text (Firefox)
A quick function to replace the selected text (in Firefox). Accepts:
- string to replace the selection, or
- callback function that takes the selected text and returns a string to replace the selection
function replaceSelection(t) { if (typeof t === 'function') { t = t(window.getSelection().toString()); } var range = window.getSelection().getRangeAt(0); range.deleteContents(); range.insertNode(document.createTextNode(t)); }
Usage:
1. Replace selected text with "dude"
replaceSelection('dude');
2. Uppercase the selected text
replaceSelection(function(s){return s.toUpperCase()});
3. Lowercase the selected text
replaceSelection(function(s){return s.toLowerCase()});
Luckily I'm so close (and yet so far) to finishing this book, otherwise I won't be able to help myself but create a whole toolbar of bookmarklets for "power" Google doc users...

October 22nd, 2008 at 9:58 am
Nice, but how about any cross-browser code? Would be great.
June 3rd, 2009 at 2:09 am
Can you write a syntax for removeformat command. The following is not working for me
var range = window.getSelection().getRangeAt(0);
document.execCommand(”Removeformat “,false,null);