mardagz mardagz - 1 year ago 47
jQuery Question

how to replace my selected text in jQuery?

how to replace selected text in html textarea?


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

function getSelectedText(){
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))};


bbrep("[b]", "[/b]");
return false;

anyone has an idea for this? :)

Answer Source

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.


Instead of using .click, use .mousedown

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