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...
This entry was posted on Thursday, March 6th, 2008 and is filed under JavaScript, writing. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

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);
October 20th, 2010 at 5:37 am
hi, any idea how do this with just one instance and not replace each occurance of a word/string?
May 26th, 2011 at 5:27 am
Hello, when I replace “toUpperCase” by “strike” or “bold” it show “selected text“. How can I change it to the “innerHTML”?