Replace One Character

[Total: 0    Average: 0/5]

This example shows how to change one character in a string.

Body Code:

<script>
/*
 * This works on 1 character only if _ONE=1
 * if _ONE=0 then it will replace all occurances.
 */
var _ONE=1;
function Switch(item,OldChar,NewChar)
{
  var _ret="";
  var _flag=0;
  var _item=item.split("");
  for(var i=0;i<_item.length;i++)
  {
    if(!_flag&&_item[i]==OldChar)
	{
	  _item[i]=NewChar;
      _flag=_ONE;
	}
	_ret+=_item[i];
  }
  return(_ret);
}


var switch1_before="this is a test";
document.write("Before Switch1: &quot;"+switch1_before+"&quot;<BR>");
    switch1_after=Switch(switch1_before," ","+");
document.write("After Switch 1: &quot;"+switch1_after+"&quot<BR>");

document.write("<HR>");

document.write("Now change all occurances.<BR>");
_ONE=0; /* change to make it sub all occurrences. */

var switch2_before="this+is+a+test";
document.write("Before Switch2: &quot;"+switch2_before+"&quot;<BR>");
    switch2_after=Switch(switch2_before,"+"," ");
document.write("After Switch 2: &quot;"+switch2_after+"&quot<BR>");
</script>

Times Viewed: 0

Leave a Reply

Your email address will not be published. Required fields are marked *