How can I use JavaScript to replace highlighted text in a form field?

For example, a user highlights the word "change", and then clicks on a "B" button. That word then becomes "[BOLD]change[/BOLD]"