// code for IE
var textarea = document.getElementById("textarea");
if (document.selection)
{
textarea.focus();
var sel = document.selection.createRange();
// alert the selected text in textarea
alert(sel.text);
// Finally replace the value of the selected text with this new replacement one
sel.text = '<b>' + sel.text + '</b>';
}
// code for Mozilla
var textarea = document.getElementById("textarea");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var sel = textarea.value.substring(start, end);
// This is the selected text and alert it
alert(sel);
var replace = '<b>' + sel + '<b>';
// Here we are replacing the selected text with this one
textarea.value = textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);