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 John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Count characters in string

Status
Not open for further replies.

simonchristieis

Programmer
Jan 10, 2002
1,144
GB
I would like to count the characters in a string

eg

str = "123456"

str.match("1")


tells me there is a match - but I want to know how many times, as this is in a document.write statement, and because of the work that the page will have to do, I also don't want to use a function.

something like this:
a new Array()
document.write(a(str.match("1")).length)


any ideas anyone?

simon
 
str = "1234561321321"

//make an array
myArr = str.split("1")

//get the count
oneCount = myArr.length + 1

//make sure that there is at least one
if(oneCount == 1){
if(!str.match("1")) oneCount = 0
}

Programming today is a race between software engineers striving to build better and bigger idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. - Rick Cook (No, I'm not Rick)

zen.gif
 
How about:

Code:
var numberOfOnes = str.length - str.replace(/1/g,'').length;

This compares the length of the string without the character-in-question (in this case, '1') to the original length. The difference is the number of times the character-in-question appears.

If the character-in-question is going to change (i.e., if you don't know ahead of time which character you want to count):
Code:
function countChars(str, characterInQuestion)
{
 var regexp = new RegExp(characterInQuestion, "g");
 var numberOfChars = str.length - str.replace(regexp,'').length;
}

'hope this helps.

--Dave
 
NOTE: if the 'characterInQuestion' could be more than one character long, you need to take its length into account:

Code:
function countChars(str, characterInQuestion)
{
 var regexp = new RegExp(characterInQuestion, "g");
 var numberOfChars = [b]([/b]str.length - str.replace(regexp,'').length[b])/characterInQuestion.length[/b];

 [b]//oh, yeah... and:
 return numberOfChars;[/b]
}

--Dave
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top