Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1726 How can I count of number of instances of a particular word or character in a string?

irt.org | Knowledge Base | JavaScript | Text | Q1726 [ previous next ]

Q1726 How can I count of number of instances of a particular word or character in a string?

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>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.