Click to See Complete Forum and Search --> : .indexOf() method
dabush
02-23-2003, 03:34 PM
ok, as we all know, the syntax for this method is
string.indexOf(x,y);
(where you find the first x starting with position y).
well, my question is, how do you find the first x before the position y?
khalidali63
02-23-2003, 04:17 PM
If I understand it correctly,
string.indexOf("x")
will return the first instance of the 'X" in the calling string.
when you provide an index as in your example it restricts it to find the "X" from the index y and beyond.
Cheers
Khalid
dabush
02-23-2003, 04:29 PM
ugh. i know that. thats exactly what i said? i want to know how to find x from Y and before (not beyond)
dabush
02-23-2003, 05:47 PM
i came up with my own way to do this. You can use it if you want. Compare this.
This is to find string x AFTER position y in the string called string
string.indexOf(x,y);
This is to find stringx BEFORE position y in the string called string
findBefore(string,x,y);
when you have the following in your script
function findBefore(string,x,y)
{
var reversed = reverse(string);
var backindex = reversed.indexOf(reverse(x),(string.length-y)) + x.length;
var fixindex = string.length - backindex;
return fixindex;
}
function reverse(string)
{
var newstr = '';
for (var loop = 1; loop <= string.length; loop++)
{
newstr += string.charAt(string.length-loop);
}
return newstr;
}
try it. it works
dabush
02-23-2003, 05:56 PM
whoah. ur smart. y didnt u say something earlier. thanks.
dabush
02-23-2003, 06:00 PM
never mind, that dont do it. it finds the first x in the string before y. but i want it to find the x before y and closest to y.
Timbuck2
02-23-2003, 07:59 PM
<grin>
Current Score
Dave = genious
Dave = da
Dave = Super Genius
Not bad for a days work