views:

2101

answers:

3

Hi,

Firstly, I am new to Javascript.

I need to count the number occurances of a character in a string.

Its something like suppose my string contains

var mainStr = "str1,str2,str3,str4";

My return value should be 3

I also need to validate that each of the strs i.e str1 or str2 or str3 or str4 should not exceed say 15 character.

Can someone please help me with this?

Thanks in Advance, Akash

+4  A: 

If you're looking for the commas:

(mainStr.split(",").length - 1) //3

If you're looking for the str

(mainStr.split("str").length - 1) //4
apphacker
mainStr.split(",").length will be 4 in this case, the other one 3.
KooiInc
good point, edited it to reflect that.
apphacker
A: 

A quick Google search got this (from http://www.codecodex.com/wiki/index.php?title=Count_the_number_of_occurrences_of_a_specific_character_in_a_string#JavaScript)

String.prototype.count=function(s1) { 
    return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}

Use it like this:

test = 'one,two,three,four'
commas = test.count(',') // returns 3
immibis
A: 

The following uses a regular expression to test the length. testex ensures you don't have 16 or greater consecutive non-comma characters. If it passes the test, then it proceeds to split the string. counting the commas is as simple as counting the tokens minus one.

var mainStr = "str1,str2,str3,str4";
var testregex = /([^,]{16,})/g;
if (testregex.test(mainStr)) {
  alert("values must be separated by commas and each may not exceed 15 characters");
} else {
  var strs = mainStr.split(',');
  alert("mainStr contains " + strs.length + " substrings separated by commas.");
  alert("mainStr contains " + (strs.length-1) + " commas.");
}
Jonathan Fingland