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

5 Responses to “replace selected text (Firefox)”

  1. zx Says:

    Nice, but how about any cross-browser code? Would be great. :)

  2. ARA Says:

    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);

  3. Devan Says:

    hi, any idea how do this with just one instance and not replace each occurance of a word/string?

  4. KM Says:

    Hello, when I replace “toUpperCase” by “strike” or “bold” it show “selected text“. How can I change it to the “innerHTML”?

  5. How to Win On Qubidz Says:

    I actually loved this brilliant article. Please continue this awesome work.

Leave a Reply