Code:
<html>
<head>
<script type="text/javascript">
// REPLACE VARIABLE VALUE IN TEXTBOX OR TEXTAREA OR DIV BY ANOTHER VALUE
function doRep(IDS, val2replace, change2, elem) {
if (elem == "T") {
var txt = document.getElementById(IDS).value; // string to be analysed
}
if (elem == "D") {
var txt = document.getElementById(IDS).innerHTML; // string to be analyzed
}
var match = new RegExp(val2replace, 'gi'); // setting regex with val2replace global and case insensitive
var output = txt.replace(match, change2); // replacing variable string with variable replacement value
if (elem == "T") {
document.getElementById(IDS).value=output;
}
if (elem == "D") {
document.getElementById(IDS).innerHTML=output;
}
}
</script>
</head>
<body>
<input type = "text" id = "txt1" value = "Now is the time for all good men to come to the aid of their country." size = "70">
<br><br>
<textarea id="txt2" cols="40" rows="5">
Now is the time for all good men
to come to the aid of their country.
</textarea>
<br><br>
<div id="divText">
Now is the time for all good men<br>
to come to the aid of their country.
</div>
<br>
Find: <input type="text" id="txt2find" value=""><br>
Replace: <input type="text" id="reptext" value=""><br>
<br><br>
<button
onclick="doRep('txt1',document.getElementById('txt2find').value,document.getElementById('reptext').value, 'T')">
Textbox: Do it</button>
<button
onclick="doRep('txt2',document.getElementById('txt2find').value,document.getElementById('reptext').value, 'T')">
Textarea: Do it</button>
<button
onclick="doRep('divText',document.getElementById('txt2find').value,document.getElementById('reptext').value, 'D')">
DIV: Do it</button>
</body>
</html>
<br><br><br>
You need to escape the 11 following characters (often called "metacharacters") IN THE FIND STRING with a backslash : <br>
the opening square bracket [, <br>
the backslash \, <br>
the caret ^, <br>
the dollar sign $, <br>
the period or dot ., <br>
the vertical bar or pipe symbol |, <br>
the question mark ?, <br>
the asterisk or star *, <br>
the plus sign +, <br>
the opening round bracket ( <br>
and the closing round bracket ). <br>