How can I replace the selected word in a textarea from JavaScript?

Ravi Verelly

A solution that works in IE5+. Credit goes to Dave Clark.

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;
<form name="f">
<textarea cols='40' rows='10' name='msg'></textarea>
<input type="button" name="b" value="Replace" onClick="replaceit();"> </form> </BODY> </HTML>
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact