replace selected text (Firefox)

March 6th, 2008. Tagged: JavaScript, writing

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...

Tell your friends about this post: Facebook, Twitter, Google+

5 Responses

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

  2. 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. hi, any idea how do this with just one instance and not replace each occurance of a word/string?

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

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

Leave a Reply