I'm really going round and round in circles with this

Basically - someone would select some text in their TEXTAREA (#post_message), and then it would replace it with the respective BBtag wrapped around:

$('.markup_btn').click( function() { 
	var selected_txt_range = $('#post_message').getSelection();
	var test = $('#post_message').val().substring(selected_txt_range.start,selected_txt_range.end);
	var thevalue = $('#post_message').val();
		thevaluenew = thevalue.replace(test,""+test+"");
	alert("Replacing: " + test + ",  GOT: " + thevalue);
	$('#post_message').val( thevaluenew );
The "test" var comes up fine with what I wanna replace... and using the getSelection() code I can get the start and end char (this is a plugin). The problem comes to when I wanna replace the actual selected part:

		thevaluenew = thevalue.replace(test,""+test+"");
That works, BUT if you have for example:

This i a test and a test again

...and you have the 2nd "test" highlighted, it would actually replace the first one (i.e it doesn't take into consideration the selected part).

Is there a way to do a substr/regex replacement just using a sub-str? I tried http://reference.sitepoint.com/javas...ta/replaceData , but this doesn't seem to work? (I get an error about it not existing as a function)

TIA - I've about had it with this function