I am currently having an annoying little problem. I am making my own BBCode editor, and coding the parser as well.
Now the problem is lets say the user enters this in the text area:
Hello my name is Michael Jones.
What is your name?
If the user highlights the first 'name', it will then edit that selected 'name' in the first line. The problem is though if the user selects the 'name' in the second sentence and tries to edit it, it will edit the first 'name' instead.
I have figured out that when using .replace
it replaces the first word found. So my question is how do I replace the correct match of the word? I am very unsure of what to do! :( Here is my code:
function getInputSelection(item){
if(typeof item != "undefined"){
start = item[0].selectionStart;
end = item[0].selectionEnd;
return item.val().substring(start, end);
}
else{
return '';
}
}
$('button[type="button"]').click(function() {
var textareavalue = $('#textareainput').val();
var highlightedvalue = getInputSelection($('#textareainput'));
var updatedvalue = '['+$(this).attr('name')+']' + highlightedvalue + '[/'+$(this).attr('name')+']';
textareavalue = textareavalue.replace(highlightedvalue, updatedvalue);
$('#textareainput').val(textareavalue)
});
$('button[type="button"], #textareainput').on('click keyup',function(){
$('#posttextareadisplay').text($('#textareainput').val());
var replacebbcode = $('#posttextareadisplay').html().replace(/(\[((\/?)(b|i|u|s|sup|sub|hr))\])/gi, '<$2>')
.replace(/(\[((align=)(left|center|right|justify))\])/gi, '<div align="$4">')
.replace(/(\[((color=#)([0-9a-fA-F]{1,}))\])/gi, '<div style="color:#$4">')
.replace(/(\[((size=)(1|2|3|4|5|6))\])/gi, '<font size="$4">')
.replace(/(\[((\/)(size))\])/gi, '</font>')
.replace(/(\[((\/)(align|color|size))\])/gi, '</div>');
$('#posttextareadisplay').html(replacebbcode);
});
If you would like more information, or more understanding of the question, please comment! :) Thank You, please help.