I have a function that takes the input from a text area, searches through the text, and should replace &, “, <, or > with &, <, etc.
As the code is now, it will replace other characters, but runs into an infinite loop when dealing with ampersands. I’m thinking it’s finding the ampersands from other things it has already replaced and trying to replace them over and over.
Does anyone have any suggestions how to improve this and break out of the loop?
[CODE]<script language=”javascript”>
function replace(){
//create array containing the four regular expressions
var re = new Array(“&”, “>”, “””, “<“);
//creates an array with the final values
var altChar = new Array(“&”, “>”, “"”, “<”);
//assign the user input to a variable
var userString=document.input.userInput.value;
//runs the search and replace for each symbol, based on it’s array position
for(var i=0; i<4; i++){
//searches the string for the symbols in each array slot
var matchStringIndex = userString.indexOf(re[i]);
//When the indexOf returns a -1, it means the search expression was not found. This loop runs while it is not equal to -1
//or, when the expression is still present in the string
while(matchStringIndex != -1){
userString = userString.replace(re[i], altChar[i]);
//runs indexOf again to see if the while loop needs to run again
matchStringIndex = userString.indexOf(re[i], (matchStringIndex+1));
}
//outputs the transformed value
document.input.userOutput.value=userString;
}
}
</script>
Here’s a link to try it out, but the loop is infinite if you search for an & and may crash your browser. Thanks everyone!