mardagz mardagz - 2 months ago 6
jQuery Question

how to replace my selected text in jQuery?

how to replace selected text in html textarea?

mardagz
to
[b]mardagz[\b]


here's my code but won't work..

function getSelectedText(){
if(window.getSelection){
return window.getSelection().toString();
}
else if(document.getSelection){
return document.getSelection();
}
else if(document.selection){

return document.selection.createRange().text;
}}



function bbrep(start, end){
$("#pPost").val($("#pPost").val().replace(getSelectedText(), start + getSelectedText() + end))};


key

$("#bbbold").click(function(){
bbrep("[b]", "[/b]");
return false;
})


anyone has an idea for this? :)

Answer

This works:

function bbrep(start, end) {
    var str = $("#pPost").val();
    var word = "bar";//getSelectedText();
    var re = new RegExp("(\\b" + word + "\\b)", "ig");
    $("#pPost").val(str.replace(re, start + "$1" + end));
};

However I had to hard-code a string because your getSelectedText() method does not return anything.

Edit:

Instead of using .click, use .mousedown

By the time .click happens, the text is no longer selected.