Forum Moderators: open

Message Too Old, No Replies

lastIndexOf in string

string last index of other string

         

tgkprog

8:08 pm on Apr 5, 2008 (gmt 0)

10+ Year Member



hi I was trying to write a function to get the last index of a string in another string. apparently the offset in index of is 1 based as

/**
* 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);
}

daveVk

2:11 am on Apr 6, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Use lastIndexOf ? or is this an academic exercise


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]

tgkprog

2:17 am on Apr 6, 2008 (gmt 0)

10+ Year Member



oops thanks i did not know that was there ... there was no trim so i assumed this not there too ... no it was not academic thank you - js just like java here