Build textarea with formatting controls - how to get selected text
<p>Just for fun, I want to build simple text formatting tools for a textarea.  To begin, I want to be able to enclose high-lighted text in a textarea with ** if it is to be in bold format (just like stackoverflow's textarea editor).  I've written the following code, which works most of the time, but it does have a bug, which I'll explain shortly.</p>

<pre><code>&lt;html&gt;
&lt;head&gt;
&lt;script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"&gt;&lt;/script&gt; 
&lt;script type="text/javascript" language="javascript"&gt;
var tmpText = '';
$(document).ready(function(){
        tmpText = '';
        $('#btn_bold').click(function(){bold(tmpText);});
        $('textarea').bind('mouseup', function(){
                  tmpText = '';
                  if(window.getSelection){
                    tmpText = window.getSelection().toString();
                  }else if(document.getSelection){
                    tmpText = document.getSelection().toString();
                  }else if(document.selection){
                    tmpText = document.selection.createRange().text;
                  }
        });
});

function bold(str)
{
        $('textarea').val($('textarea').val().replace(str,'**'+str+'**'));
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;button type="button" id="btn_bold"&gt;bold it&lt;/button&gt;
&lt;textarea&gt;AA&lt;/textarea&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>So if you high-light the first letter A and bold it, you'll get the result <code>**A**A</code>.  But if you high-light the second letter A and bold it, you still get <code>**A**A</code>, instead of <code>A**A**</code> because the line of code <code>$('textarea').val($('textarea').val().replace(str,'**'+str+'**'));</code> is insufficient at identifying which letter A you want to bold.</p>

<p>What's an efficient way to identify high-lighted text and bold it?</p>
