Forum Moderators: open
/**
* last index of find string in item string or -1 if not there at all.
*/
function lastIndex(item, find) {
var i = item.indexOf(find);
var old = i;
var y = i;
//alert("last indfex item [" + item + "] find [" + find + "] i " + i );
while(i > -1){
y = item.indexOf(find, i+1);
i = y;
//alert("last indfex item [" + item + "] find [" + find + "] i " + i );
if(i>-1){
old=i;
}
}
return old;
}
did not work
instead i had to use y = item.indexOf(find, i+2);
so full code
/**
* last index of find string in item string or -1 if not there at all.
*/
function lastIndex(item, find) {
var i = item.indexOf(find);
var old = i;
var y = i;
//alert("last indfex item [" + item + "] find [" + find + "] i " + i );
while(i > -1){
y = item.indexOf(find, i+2);
i = y;
//alert("last indfex item [" + item + "] find [" + find + "] i " + i );
if(i>-1){
old=i;
}
}
return old;
}
test code
function tst_lastIndex() {
s="aad";
i=lastIndex(s, " ");
//alert("tst_lastIndex -1 :" + (i == -1)+ " " + i);
s="aad a";
i=lastIndex(s, " ");
//alert("tst_lastIndex space in [" +s+ "] 3 :" + (i== 3) + " " + i);
s="aad fn a";
i=lastIndex(s, " ");
alert("tst_lastIndex space in [" + s + "] 6 :" + (i== 6) + " " + i);
s="123 56 8 0 12";
i=lastIndex(s, " ");
alert("tst_lastIndex space in [" + s + "] 11 :" + (i== 11) + " " + i);
}
strObj.lastIndexOf(substring[, startindex])
Arguments
strObj
Required. A String object or literal.
substring
Required. The substring to search for within the String object.
startindex
Optional. Integer value specifying the index to begin searching within the String object. If omitted, searching begins at the end of the string.
Did following test of indexOf in IE
"abcb".indexOf( 'b',0 )
1
"abcb".indexOf( 'b',1 )
1
"abcb".indexOf( 'b',2 )
3
looks ok to me.
[edited by: daveVk at 2:42 am (utc) on April 6, 2008]