View Full Version : get all indexes from indexOf()
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
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);
|
vBulletin® v3.8.5, Copyright ©2000-2012, Jelsoft Enterprises Ltd.