PDA

View Full Version : Javascript error


misheck
12-08-2008, 06:00 PM
I am studying javascript and I have stumbled accross an exercise section where the script is not working. It is suppose to write the number of occurrences of the word Wrox. <script language="JavaScript" type="text/javascript">
var myString = "Welcome to Wrox books. ";
myString = myString + "The Wrox website is www.wrox.com. ";
myString = myString + "Visit the Wrox website today. Thanks for buying Wrox";

var foundAtPosition = 0;
var wroxCount = 0;

while ( foundAtPosition != -1)
{
foundAtPostion = myString.indexOf("Wrox",foundAtPosition);
if (foundAtPosition != -1)
{
wroxCount++;
foundAtPosition++;
}
}

document.write("There are " + wroxCount + " occurrences of the word Wrox");


</script> The last foundAtPosition++; is meant to stop the script from running infinitely but it seems to be running continously and not writing anything to the screen.

coothead
12-09-2008, 05:55 AM
Hi there misheck,

have a look at this simpler method...

<script type="text/javascript">

myString='Welcome to Wrox books.';
myString=myString+'The Wrox website is www.wrox.com.';
myString= myString +'Visit the Wrox website today. Thanks for buying Wrox';

matches=myString.match(/Wrox/g);

/*** use this if you want a count of all instances of wrox ****

matches=myString.match(/Wrox/gi);

**************************************************************/

wroxCount=matches==null?0:matches.length;

alert("There are " + wroxCount + " occurrences of the word Wrox");

</script>

misheck
12-09-2008, 12:17 PM
Thanks for the help. I also managed to sort out the first code I had written. I had made a mistake on the word Position I had put the word Postion

coothead
12-09-2008, 12:27 PM
Hi there misheck,

I did see the replies to your problem over at Coding Forums. (http://www.codingforums.com) :agree: