Word Replacement

[Total: 0    Average: 0/5]

This example replaces words.

Head Code:

<SCRIPT>

/*
 * This will find and change any word that is followed by a space
 * or is the last word.
 *
 * It does not find/change words that are followed by non-characters.
 * (need to fix this)
 */
function replaceChars(out,add) {
  var temp = "" + document.subform.text.value;
  out+=" ";
  add+=" ";
  var pos=0;
  var a=0;
  var i=0;
  while (temp.indexOf(out)>-1)
  {
    if(a++>10){alert('10');return;}
    pos= temp.indexOf(out);
    temp = "" + (temp.substring(0, pos) + add + temp.substring((pos + out.length), temp.length));
  }
  alert(temp.substring(temp.length-out.length,temp.length)+"n"+" "+out.substring(0,out.length-1));
  /*
   * Special case of last word on line
   */
  if(temp.substring(temp.length-out.length,temp.length)==" "+out.substring(0,out.length-1))
    temp=""+temp.substring(0,temp.length-out.length+1)+add.substring(0,add.length-1);
  document.subform.text.value = temp;
}

</script>

Body Code:

This will replace all occurrances of the word "the" with "xxx".

<form name="subform">

<input type=text name=text size=40 value="the these those this the the"><br>
<input type=button name=action value="replace" onClick="replaceChars('the','xxx');">


</form>

Times Viewed: 1

Leave a Reply

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