Click to See Complete Forum and Search --> : counting commas
Hello, i would like to count the number of times a comma apears in a string.
For example "asd,wererw.2345,345.@qwer" would be 2.
I need this in Function format for example
function CountCommas(){
var commas = ? document.form1.txtString.value;
alert("There are "+commas+" in your string");
}
ofcourse that's not correct but that's the idea.
Thanks!:D
Khalid Ali
07-10-2003, 09:44 AM
code below should do that for you..
<script type="text/javascript">
<!--
String.prototype.CountCommas = function(){
return (this.split(",")).length-1;
}
function Process(){
var frm = document.getElementById("form1");
var len = frm.length;
alert(frm.t1.value.CountCommas())
}
//-->
</script>
</head>
<body class="body">
<form id="form1" action="" onsubmit="">
<input type="text" name="t1"/>
<input type="button" value="Count" onclick="Process()"/>
</form>
var NumberOfCommas=document.form1.txtString.value.match(/,/g).length
Charles
07-10-2003, 09:47 AM
I would expect that the following would work.
String.prototype.commaCount = function () {return this.match(/,/g).length}
alert ('asd,wererw.2345,345.@qwer'.commaCount())
freefall
07-10-2003, 09:53 AM
Well then I'll take the long, easy version
<script type="text/javascript">
function CountCommas(){
var i = 0;
var commas = null;
var txt = document.forms[0].txtString.value;
while (i<1000)
{
i++;
if (txt.search(",") != -1)
{
commas++;
txt = txt.substr(txt.indexOf(",")+1, txt.length);
}
else
i = 101;
}
alert("There are "+commas+" commas in your string");
}
</script>
- Ian
Charles
07-10-2003, 09:57 AM
It's certainly longer but I don't quite see how it's easier. And it'll take a great deal more time to run.
freefall
07-10-2003, 10:08 AM
sorry, easier *for me*
because I don't know about regular expressions and all that other stuff, but I agree the shorter ones are much better
- Ian
Thanks all, works great!:D