How can I replace the selected word in a textarea from JavaScript?
Created May 7, 2012
Ravi Verelly A solution that works in IE5+. Credit goes to Dave Clark.
<HTML> <HEAD> <TITLE>replace</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!--// var seltext = null; var repltext = null; function replaceit() { seltext = (document.all)? document.selection.createRange() : document.getSelection(); var selit = (document.all)? document.selection.createRange().text : document.getSelection(); if (selit.length>=1){ if (seltext) { repltext= prompt('Please enter the word to replace:', ' '); if ((repltext==' ')||(repltext==null)) repltext=seltext.text; seltext.text = repltext; window.focus() } } } //--> </SCRIPT> </HEAD> <BODY> <form name="f"> <textarea cols='40' rows='10' name='msg'></textarea>
<input type="button" name="b" value="Replace" onClick="replaceit();"> </form> </BODY> </HTML>