how to replace my selected text in jQuery?

jquery replace text in div
jquery find and replace html
jquery replacewith not working
replace class 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? :)

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.

Replacing selected HTML text in jQuery, Try this: function getSel() // javascript { console.log("test"); // obtain the object reference for the textarea> var txtarea = document. Definition and Usage. The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed).

Here a complete tested & working example

function getSelectedText() {
    var len =$("#pPost").val().length;
    var start = $("#pPost")[0].selectionStart;
    var end = $("#pPost")[0].selectionEnd;
    var sel = $("#pPost").val().substring(start, end);
    return sel;
}


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

}

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

})

here is the html code snipet

<textarea rows="2" cols="20" id="pPost">mardagz
</textarea>
<input type="button" id="bbbold" value="clcikMe" />

here is a jsfiddle example i just did "it works"


Another jsfiddle that takes the index into account too, jsfiddle.net/SU7wd/58 <- works on that second a too

Replace selected text from input fields on button click, A function that returns content with which to replace the set of matched elements. An element could also be selected as the replacement: text-align: center;. Inside our event handler function, we changed the text of our “message” div by using JQuery’s text method. Note that the text method will not accept HTML. If you attempt to use a paragraph tag, for example, then the text method will escape your HTML and your p tag will end up being displayed in the browser.

Just in case someone comes here later, I'll share my solution I found after some research, based on what's said above. I was looking for a solution that would replace what I ask to replace (and not the same substrings somewhere in the textarea), and also to leave with the focus at the end of the inserted text.

Here's the solution I came to:

function text_with_insert(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}    

function surround_sel_text( str_start, str_end ) {
  var el = $("#pPost");
  var focus_idx = el[0].selectionEnd + str_start.length + str_end.length;

  var text_with_end_insert = text_with_insert( el.val(), el[0].selectionEnd, str_end );
  el.val( text_with_insert( text_with_end_insert, el[0].selectionStart, str_start ) );
  el[0].selectionStart = focus_idx;
  el[0].selectionEnd = focus_idx;
}

$("#bbbold").on('mousedown' ,function() {
      surround_sel_text( '[b]', '[/b]' );
      event.preventDefault();     
});

.replaceWith(), The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes. To change text inside an element using jQuery, use the text() method. Example. You can try to run the following code to replace text inside an element:

Ok I had to rebuild this to work with my asp.net control. Think it about as simple as it will get. This one will replace what selected, and not the first word found like in the others.

Just make sure you give it the ID of your textbox.

You can call the function like this makeBBCode("[b]", "[/b]") . I Used OnClientClick on a asp image button to call it. [Ex: OnClientClick='makeBBCode("[b]", "[/b]")']

    String.prototype.insertAt = function (index, string) {
        return this.substr(0, index) + string + this.substr(index);
    }

    function makeBBCode(start, end) {
        var txtBox = document.getElementById("Object_Id_Here")
        txtBox.value = txtBox.value.insertAt(txtBox.selectionEnd, end).insertAt(txtBox.selectionStart, start);
    }

.select(), the javascript string.replace method actually takes a RegExp as it's first argument. Without specifying it as 'greedy' it will only match the first. jQuery Tutorial jQuery HOME jQuery Replace the first <p> element with new text: $("button").click(function() How to use a function to replace selected

You can use:

https://github.com/timdown/rangyinputs

And simply call: replaceSelectedText

How to replace selected text with javascript or jquery in content , Replace the first <p> element with new text: $("button").click(function(){ and Usage. The replaceWith() method replaces selected elements with new content. The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. Note: If you are replacing a value (and not a regular expression ), only the first instance of the value will be replaced.

[Solved] Replacing selected text - HTML / JavaScript, It specifies the new text content for the selected elements containing the HTML tags. function(index, curContent): It is optional parameter. It� The second is the text value of the select. For example, using the following select box:

jQuery replaceWith() Method, How to change the text of a label using JavaScript ? How to get the text without HTML element using JavaScript ? Self-Typing Text Effect using� The change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the

JQuery, To replace only text inside a div using jQuery, use the text() method. Example. You can try to run the following code to replace text inside a div:

Comments
  • Start out by seeing if getSelectedText() returns anything.
  • still the same... broo whheww
  • your getSelectedText method doesn't seem to be returning anything in google chrome.
  • owhh, i think so, but you have any function to fix this bro? :)
  • Very relevant
  • anyway iv'e added this one $(this).live('mouseup', function() { selection = getSelectedText(); }); there's a result but [b][/b]mardagz instead of [b]mardagz[/b]
  • Again... use mousedown not mouseup or click you have to catch it before the selection goes away.
  • owhhh i got it bro :) hihi, i just generating new function :) hihi, thanks a lot anyway.. :)
  • It should be noted that this will always replace the FIRST occurrence of the selected text, not necessarily the selected text. IE: try replacing the second 'a' in mardagz or one of the many 'a's in abracadbra...
  • @ChrisKerekes, for that all you have to do is a better replace , one that will take the index into account, take a look jsfiddle.net/SU7wd/58 <- works on that second a too