PDA

View Full Version : searching for a word in a string and counting its number of occurence


emz
04-09-2007, 07:11 PM
hi there. ok i have developed several split arrays from several strings. like this

var s1=<b>page-1</b> <b>page-2</b> <b>page-3</b>;
var s2=<b>page-1</b> <b>page-2</b> <b>page-3</b>;
var s3=<b>page-1</b> <b>page-2</b> <b>page-3</b>;

var spt=new Array()
spt[0]=s1.spit(" ");
spt[1]=s2.spit(" ");
spt[2]=s3.spit(" ");

ok what i want is to search for the word page-3 in the srtings and count the number of times it has occured, put the result in a text box.(the textbox bit is easy but getting the count......)

how do i do this.pleaaaaaaaaaaaaaase! help its urgent

Jon Hanlon
04-09-2007, 07:32 PM
var s1="<b>page-1</b> <b>page-2</b> <b>page-3</b>";
var s2="<b>page-1</b> <b>page-2</b> <b>page-3</b>";
var s3="<b>page-1</b> <b>page-2</b> <b>page-3</b>";

var spt=new Array()
spt[0]=s1.split(" ");
spt[1]=s2.split(" ");
spt[2]=s3.split(" ");

var count = 0;
var regEx = new RegExp("page-3");
for (var i=0; i<spt.length; i++) {
for (var j=0; j<spt[i].length; j++) {
if (regEx.test(spt[i][j])) count++;
}
}
alert(count);

emz
04-09-2007, 08:04 PM
let me rephrase it like this

var s1=<b>page-1</b> <b>page-2</b> <b>page-3</b>;
var s2=<b>page-4</b> <b>page-5</b> <b>page-6</b>;
var s3=<b>page-7</b> <b>page-8</b> <b>page-9</b>;

var spt=new Array()
spt[0]=s1.spit(" ");
spt[1]=s2.spit(" ");
spt[2]=s3.spit(" ");

what i need is to display the number of pages available, by getting the number of occurences of the word page. now if there is a way one can count the word "page" alone ignoring the rest "-1..."

the solution you gave me befor only brings back the size of the spt[] array in this case it alerts 3.

sorry for the mistake befor.pliz help

Jon Hanlon
04-10-2007, 06:30 PM
Um, that's what you asked for.
ok what i want is to search for the word page-3 in the srtings

Change
var regEx = new RegExp("page-3");
To
var regEx = new RegExp("page-");

emz
04-12-2007, 07:35 AM
itried that and it only displayed 1. anyway i got a way around it by using match()

thanks anyway