Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Counting specific characters in a check box

Status
Not open for further replies.

Garabaldi

Technical User
Jan 16, 2002
61
0
0
CA
Hi,

I need some javascript that will go through a textbox and tell me how many "a"s a user has entered and how many "b"s so on and so forth... I am not trying to count all the letters of the alphabet... I only need to concentrate on a certain few.

Thanks.
 
Code:
<script>
[green]// Extends the String object.
// Returns the number of occurrences a string appears
// within a string or -1 if not found.
[/green]String.prototype.contains = function(str)
{
  var re = new RegExp(str, "gi");
  var result = this.match(re);
  return result ? result.length : -1;
}

[green]// Usage:[/green]
var myString = "abcabca";
alert(myString.contains("a"));

[green]// Or:[/green]
alert("abcabca".contains("a"));
</script>



Adam
 
Dan, both the match (string method) and exec (regexp method) will return an array based on the matches found in the string. They are pretty handy tools [smile]

-kaht

[small] <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
[banghead] [small](He's back)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top