How To Wrap or Surround Highlighted Text With An Element

Rumman Ansari   2022-12-30   Developer   web development > JavaScript   268 Share

Add this library of jquery


<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script>

<script>
   function wrapText(elementID, openTag, closeTag) {
    alert
    var textArea = $('#' + elementID);
    var len = textArea.val().length;
    var start = textArea[0].selectionStart; 
    var end = textArea[0].selectionEnd;
    var selectedText = textArea.val().substring(start, end);
    var replacement = openTag + selectedText + closeTag;
    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}  
</script>

<input type="button" onclick="wrapText('myTextArea', '<b>', '</b>')" value="Surround">
<textarea id ="myTextArea">One two three four  <textarea>