Replacing BB code in text-area?


I’m really going round and round in circles with this :frowning:

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,"[b]"+test+"[/b]");
	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,"[b]"+test+"[/b]");

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 , 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 :x


I knew as soon as I posted a question I would find an answer! Here’s the solution in case anyone else is trying the same thing:

Call with:


…and it would wrap the selected text in xcxxx

				function wrapTag(tag) {
				  var textarea = document.getElementById('post_message');
				  wrapText(textarea, '[' + tag + ']', '[/' + tag + ']');
				function wrapText(element, pre_text, post_text) {
					if (element.setSelectionRange) {
						var start = element.selectionStart;
						var end = element.selectionEnd;
						element.value = element.value.substr(0, start) + pre_text + element.value.substr(start, end - start) + post_text + element.value.substr(end, element.value.length);
						setSelectionRange(element, start + pre_text.length, end + pre_text.length);
					else if (document.selection) {
						var range = document.selection.createRange();
						if (range.parentElement() != element)
						var len = range.text.length;
						range.text = pre_text + range.text + post_text;
						range.moveEnd('character', -post_text.length);
						range.moveStart('character', -len);;
					else {
						element.value += pre_text + post_text;