Alf Moh Alf Moh - 1 year ago 86
Javascript Question

indexOf and lastIndexOf in Javascript

var home = "Home sweet home";

How do you find the index of the second "e" in sweet since both home.indexOf("ee") and home.lastIndexOf("ee") both return 7. If JS takes "ee" as one unit and returns its' index, why can't it return the lastIndexOf that unit?

Answer Source

lastIndexOf returns the index of the first character in the substring where the substring appears last in the superstring.

var home = "Home sweet sweet home";
//                       ^ Matches here

To find the second e when it forms part of the string ee, use indexOf and then add 1 (you know the second character of ee is 1 character past the first character of the substring, so you know to add that much, if you want the last character of the substring, then you can calculate it using the .length of the substring).

var home = "Home sweet home";
//                  ^ Matches here
console.log(home.indexOf("ee") + 1);

To find the second e when it may or may not form part of the string ee, use indexOf to find the first e, and then use it again passing the index of the character after first e as the second argument.

var home = "The fox ate the chicken";
//            ^       ^ Matches in these places
var first_index = home.indexOf("e");
var second_index = home.indexOf("e", first_index + 1);
console.log(first_index, second_index);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download