Home : Internet : JavaScript : Text : Find/Replace

Replace Characters Using JavaScript

This page shows how to find and replace characters in a text string. The following example shows how it works:


Replace all instances of: with:

You don't have to use a form like this example — the script can be customized to suit your needs. This example is just intended to show you the concept.

First of all, place this code in the document head:

<script type="text/javascript">
function replaceCharacters() {
var origString = document.form1.inTB.value;
var inChar = document.form1.inC.value;
var outChar = document.form1.outC.value;
var newString = origString.split(inChar);
newString = newString.join(outChar);
document.form1.outTB.value = newString;
}
</script>

Place the following code in the document body:

<form name="form1" method="post" action="">
<input name="inTB" type="text" id="inTB" value="Original text string" size="30">
<br>
Replace all instances of:
<input name="inC" type="text" id="inC" value="tr" size="4">
with:
<input name="outC" type="text" id="outC" value="w" size="4">
<br>
<input type="button" name="Capitalize" value="Replace Now" onClick="replaceCharacters();">
<br>
<input name="outTB" type="text" id="outTB" value="" size="30">
</form>