Can anyone help me understand this string method?

i am having trouble understanding the second parameter when it is with LastIndexOf()…

<h2>JavaScript String Methods</h2>

<p id="demo"></p>

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate", 15);
document.getElementById("demo").innerHTML = pos;

position always ends up at 7 and how is that from backward when the parameter is set at 15?

Also,no matter how i change the second parameter it stays the same until 20 or 21.

lastIndexOf - is the last occurence
The integer is the position where you start to search from going backwards, if its ommitted then the it will search the whole string.

Hey thank you very much for your time man.
can u plz tell me how would you count it backward from that starting position(15)?

It is an already defined function. Here is a link that will explain how it works:

1 Like

Yes,i already got stuck in w3 and came here.I understand the lastIndex method without any trouble.
where i am stuck is,

Do i count and find this start value, which is 15 in this case, from backward?like," ! " and find for that word toward the beginning from there?

The method goes to the index you provide (counting from the start), goes backwards through the string, and returns the FIRST match it finds.
Why don’t you play with it and try it out? Here’s an example:

const str = 'aaZbbZcc';

console.log(str.lastIndexOf('Z', 0)); // -1
console.log(str.lastIndexOf('Z', 1)); // -1
console.log(str.lastIndexOf('Z', 2)); // 2
console.log(str.lastIndexOf('Z', 3)); // 2
console.log(str.lastIndexOf('Z', 4)); // 2
console.log(str.lastIndexOf('Z', 5)); // 5
console.log(str.lastIndexOf('Z', 6)); // 5
console.log(str.lastIndexOf('Z', 7)); // 5
console.log(str.lastIndexOf('Z', 8)); // 5
console.log(str.lastIndexOf('Z', 1000)); // 5
1 Like

Thank you guys!Finally got hold of this. :slight_smile:
u guys are awesome!