JRS: In article <SM******************************@comcast.com>, dated
Sat, 12 Aug 2006 14:18:48 remote, seen in news:comp.lang.javascript,
Randy Webb <Hi************@aol.composted :
>libsfan01 said the following on 8/12/2006 1:34 PM:
>how do u get js to work out the number of times a given char occurs in
a given string?
>var origString = "My mama told me";
var characterToCount = "m";
RE = new RegExp("[^" + characterToCount + "]", "gi")
Answer = origString.replace(RE, "").length
Omit the i to count only lower-case.
To count non-overlapping multi-length items, use something similar to
remove all occurrences and then see how much shorter it gets.
var orig = "My mama told me";
var Count = "ma";
RE = new RegExp(Count, "gi")
Answer = (orig.length - orig.replace(RE, "").length) / Count.length
Note that it counts in the string, and not in the literal which
generated it. Consider orig = "\u0033" ; Count = "3" giving 1.
Read the newsgroup FAQ.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/>? JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.