PDA

View Full Version : get all indexes from indexOf()


spy
02-13-2006, 01:30 AM
hello guys!...does anybody knowshow to get the times a word is repeated in a text and the position of each one?
i used indexOf(), but it returns just the first one

oka_
02-13-2006, 01:51 AM
The second argument of the indexOf function is "startIndex", i.e. the index to start searching from.

So you can write a loop to keep searching from the current index until indexOf returns negative.

I haven't tested this code but I imagine it would go something like this:

var c_index = 0;
var results = new Array();

while (myString.indexOf("foo", c_index) != -1)
{
c_index = myString.indexOf("foo", c_index);
results.push(c_index);
}



Let me know if it works :)

Slowburn
02-13-2006, 07:22 AM
/**
* fullIndexOf:Function
* @param strString:String the `Haystack`
* @param strToken:String the `Needle`
* @returns Array; the index of each `needle` in the `haystack`
*/
function fullIndexOf(strString:String, strToken:String):Array {
var numPosition:Number = 0, arrResult:Array = [];
do {
if ((numPosition = strString.indexOf(strToken, numPosition)) != -1) {
arrResult[arrResult.length] = numPosition;
} else {
break;
}
} while(numPosition += strToken.length);
return arrResult;
}
//
//* Usage
//*
var myString:String = "1foo is the13foo where24foo exists";
var myToken:String = "foo";
var myResults:Array = fullIndexOf(myString, myToken);
trace(myResults);