Okay so basically I have a form with a textarea
where users can add content and apply some bbcode to the selected text.
Now I get the selected text with this function:
selection_get: function() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
And that works properly, the only issue is if there is duplicate content like this for example:
You what, you what...
Now say I select the second you what
from the string above and run it through something like this:
// get the selected text
var text = selection_get();
var original_text = $('textarea').val();
var newtext = '[b]you what[/b]';
$(container).val(original_text.replace(text, newtext));
Now newtext
would be the selected code with the bbcode applied (for the sake of this example, we'll have it set as [b]you what[/b]
).
The issue is that replace()
will replace the very first occurrence of the selected text
. How do I replace the actual selected text in its set position?
Note: Please ask if I need to clarify more, the question is rather vague :-( Cheers.