You are here: irt.org | FAQ | JavaScript | Text | Q1726 [ previous next ]
Use the String object's split() method to split the string at each occurence of the word or character into an array of substrings. Then subtract one from the length of the array to calculate how many instances there are. For example:
<html> <head> <script language="JavaScript"><!-- function countInstances(string, word) { var substrings = string.split(word); return substrings.length - 1; } //--></script> </head> <body> <form> <input type="text" name="string" value="To count how many o characters are in this line, the answer should be six, press the button"> <br> <input type="text" name="word" value="o"> <br> <input type="button" value="count instances" onClick="alert(countInstances(this.form.string.value, this.form.word.value))"> </form> </body> </html>