473,386 Members | 1,973 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

number of times a character occurs in a string

hi all

how do u get js to work out the number of times a given char occurs in
a given string?

regards

Marc

Aug 12 '06 #1
7 27921
libsfan01 said the following on 8/12/2006 1:34 PM:
hi all

how do u get js to work out the number of times a given char occurs in
a given string?
You count them. Seriously, there is no built in "howManyTimesItOccurs"
type function. You will have to write your own. You also have to decide
whether "M" and "m" are the same or not.

Simple start, there are other ways also that use charAt:

var origString = "My mama told me";
var characterToCount = "m";
var counter = 0;

//if you don't want "M" and "m" to count the same
//remove the .toLowerCase() from the line below

var myArray = origString.toLowerCase().split('');
for (i=0;i<myArray.length;i++)
{
if (myArray[i] == characterToCount)
{
counter++;
}
}
alert('The character ' + characterToCount + ' appears ' +
counter + ' times in the sequence:\n' + origString)

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Aug 12 '06 #2
Randy Webb wrote:
Simple start, there are other ways also that use charAt:
[...]
I don't know if this is generally faster or slower, but I think it's
cleaner:

var str =
"hjahjkahjkahjaguyayafhajagjhajAahkjahkAjahkjahAkj ahkjahkjahkjahkjahkja";
String.prototype.count = function(match) {
var res = this.match(new RegExp(match,"g"));
if (res==null) { return 0; }
return res.length;
}
alert(str.count("a"));
alert(str.count("[Aa]"));

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Aug 12 '06 #3
Matt Kruse said the following on 8/12/2006 3:04 PM:
Randy Webb wrote:
>Simple start, there are other ways also that use charAt:
[...]

I don't know if this is generally faster or slower, but I think it's
cleaner:
It's definitely different :)
var str =
"hjahjkahjkahjaguyayafhajagjhajAahkjahkAjahkjahAkj ahkjahkjahkjahkjahkja";
String.prototype.count = function(match) {
var res = this.match(new RegExp(match,"g"));
if (res==null) { return 0; }
return res.length;
}
alert(str.count("a"));
alert(str.count("[Aa]"));
Is "match" a good name for a parameter? I don't normally use variable
names that are used by JS itself but just curious.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Aug 12 '06 #4
Thanks again Randy that worked a treat!

regards

marc
Randy Webb wrote:
libsfan01 said the following on 8/12/2006 1:34 PM:
hi all

how do u get js to work out the number of times a given char occurs in
a given string?

You count them. Seriously, there is no built in "howManyTimesItOccurs"
type function. You will have to write your own. You also have to decide
whether "M" and "m" are the same or not.

Simple start, there are other ways also that use charAt:

var origString = "My mama told me";
var characterToCount = "m";
var counter = 0;

//if you don't want "M" and "m" to count the same
//remove the .toLowerCase() from the line below

var myArray = origString.toLowerCase().split('');
for (i=0;i<myArray.length;i++)
{
if (myArray[i] == characterToCount)
{
counter++;
}
}
alert('The character ' + characterToCount + ' appears ' +
counter + ' times in the sequence:\n' + origString)

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Aug 12 '06 #5
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.
Aug 12 '06 #6
Matt Kruse wrote:
Randy Webb wrote:
>Simple start, there are other ways also that use charAt:
[...]

I don't know if this is generally faster or slower, but I think it's
cleaner:

var str =
"hjahjkahjkahjaguyayafhajagjhajAahkjahkAjahkjahAkj ahkjahkjahkjahkjahkja";
String.prototype.count = function(match) {
var res = this.match(new RegExp(match,"g"));
if (res==null) { return 0; }
return res.length;
}
alert(str.count("a"));
alert(str.count("[Aa]"));
What about
var str =
"hjahjkahjkahjaguyayafhajagjhajAahkjahkAjahkjahAkj ahkjahkjahkjahkjahkja";

alert( str.length - str.replace(/a/gi,'').length);
Andrew Poulos
Aug 12 '06 #7
JRS: In article <8d******************************@comcast.com>, dated
Sat, 12 Aug 2006 15:36:46 remote, seen in news:comp.lang.javascript,
Randy Webb <Hi************@aol.composted :
>Matt Kruse said the following on 8/12/2006 3:04 PM:
>var str =
"hjahjkahjkahjaguyayafhajagjhajAahkjahkAjahkjahAk jahkjahkjahkjahkjahkja";
String.prototype.count = function(match) {
var res = this.match(new RegExp(match,"g"));
if (res==null) { return 0; }
return res.length;
ISTM that return +res.length should do for those 2 lines.
>}
>alert(str.count("a"));
alert(str.count("[Aa]"));

Is "match" a good name for a parameter? I don't normally use variable
names that are used by JS itself but just curious.
It's not a good name, at least in contexts like that, if only because it
raises doubts such as that in the mind of the reader. Synonyms exist.

--
© 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.
Aug 13 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Michael Onfrek | last post by:
Hi! I'm playing with entry again and trying to restrict length of entry widget to certain number of character, so users cannot enter more character into it. Any ideas? Reg. Michael Onfrek
6
by: Mr. B | last post by:
I want to return the name of the drawing file (DWG) from the end of a string. The string will be of varying lengths... as well as the drawing file name itself. I could do it the long way by...
25
by: Jason | last post by:
Hi, below is example code which demonstrates a problem I have encountered. When passing a number to a function I compare it with a string's size and then take certain actions, unfortunately during...
2
by: Dan McCloud | last post by:
Is there anything 'wrong' with setting the value of a drop down menu using the following? document.frmStep1.drpInvaddress.value = 'A1020761603!>\>R2' This string is a key in our database that...
7
by: P. Schmidt-Volkmar | last post by:
Hi there, I have a string in which I want to calculate how often the character ';' occurs. If the character does not occur 42 times, the ";" should be added so the 42 are reached. My...
3
by: sunmat | last post by:
To find number of character without space using java Example: String = prabu sun No. of char =8 plz send me code
3
by: shaif | last post by:
Hey I have a simple problem that How i can get set of character from String, such as: Dim s as string Dim s1 as string s="73421482716@bffsdffhjxyz783djk"; s1="xyz"; How it is possible that...
2
by: karanbikash | last post by:
hi , I have a column with datatype as decimal(31,2) . The data is like 123456.67 , 7634578.99 Is it a way to convert the entire number into character . like '1232456.67' . The output...
7
kireytir
by: kireytir | last post by:
hi all, this is my code (in interrupt function) for finding character in string (data). Ekle_text.Text += data; string veri = Ekle_text.Text; int found = veri.IndexOf("x"); if (found !=...
4
by: Chendil | last post by:
Hi, I want to write a perl script to count the number of character(case insensitive) in a file. let me know if this is write way to do this. open(IN,"words.txt"); $count=0; $char="a";
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.