How to correctly grab and replace selected text in JavaScript? <p>Here is code: </p> <pre><code>var selection; var edited_selection; var value; var string; $("#text").select(function(){ // $("#text") is textarea value = $("#text").val(); selection = window.getSelection(); string = selection.toString(); }); $("#bold").click(function(){ edited_selection = "&lt;b&gt;" + string + "&lt;/b&gt;"; var replacing = value.replace(string, edited_selection); $("#text").val(replacing); }); </code></pre> <p>When I click on some common number or character, it will wrap the first occurence of that character or number. For example easy sentence: "Hello there". If I will try to select the last "e" from that sentence, it will select the first occurence of "e" and it will wrap like <b>e</b>, but i wanted to select the last "e". How can I do it? Thank you for answers. </p>