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;

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">
Replace all instances of:
<input name="inC" type="text" id="inC" value="tr" size="4">
<input name="outC" type="text" id="outC" value="w" size="4">
<input type="button" name="Capitalize" value="Replace Now" onClick="replaceCharacters();">
<input name="outTB" type="text" id="outTB" value="" size="30">
Subscribe to us on YouTube