You are here: irt.org | FAQ | JavaScript | Text | Q771 [ previous next ]
When replacing text within a string with another item of text you can use the following robust function:
<SCRIPT LANGUAGE="JavaScript"><!-- function replace(string,text,by) { // Replaces text with by in string var strLength = string.length, txtLength = text.length; if ((strLength == 0) || (txtLength == 0)) return string; var i = string.indexOf(text); if ((!i) && (text != string.substring(0,txtLength))) return string; if (i == -1) return string; var newstr = string.substring(0,i) + by; if (i+txtLength < strLength) newstr += replace(string.substring(i+txtLength,strLength),text,by); return newstr; } //--></SCRIPT>
To replace 'X' with 'Y' use:
<SCRIPT LANGUAGE="JavaScript"><!-- var mytext = 'xXyY'; var myresult = replace(mytext,'X','Y'); //--></SCRIPT>
For an explanation of the replace() function see the article How long is a piece of string?.
To replace two characters, for example to change \n to ^ use:
<SCRIPT LANGUAGE="JavaScript"><!-- mytext = 'this is a line \nthis is another\n'; var myresult = replace(mytext,'\n','^'); //--><SCRIPT>
To replace text within a form field use:
<FORM NAME="myForm"> <INPUT TYPE="TEXT" NAME="myText" VALUE="ab aa bb a b ba aabababb"> <INPUT TYPE="BUTTON" VALUE="Replace" onClick="this.form.myText.value=replace(this.form.myText.value,'ab','xy')"> </FORM>