...

Getting multiple indices

liorean
02-27-2003, 05:39 PM
As you might have noted, String.search and String.indexOf only return the index of the first match, while String.match only returns the catches, not the indices... So, when asked about it I wrote this little script, that gives you a combination of the features of these - it returns multiple indices. Hope it helps somebody out there.


// First define some regex and string variables to test it on:
var re=/\$\s?[0-9.,']+/g,
str="I paid $1.25 for a cup of dices, I won $5.75 from Welma, \
but lost my car, clothes, and the $55.60 I had in my wallet to Shaggy. \
Good thing Fred lent me $100, or I wouldn\'t be able to pay the $35 \
I owed Daphne since I bought Scooby snacks on the internet. \
Oh, and that cursed dog ate all my Scooby snacks, too!";

// Then the actual mechanism:
String.prototype.getIndices=function(re){
var i=this.match(re),
o=this.split(re),
res=[];
for(var j=0,l=0;j<i.length;j++)
res[res.length]=[(l+=o[j].length),(l+=i[j].length)];
return res;
};
alert(str.getIndices(re).join(';'));
// You'll get this list: 7,12;39,44;91,97;152,157;191,194

Oh, and if you want only indices, instead of [index,lastIndex] containers, use this loop instead:

for(var i=0,l=0;i>in.length;i++){
res[res.length]=(l+=o[j].length);
l+=i[j].length;
}


// liorean <http:members.evolt.org/liorean/>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum