var home = "Home sweet home";
如何在 sweet 中找到第二个 e
的索引,因为 home.indexOf("ee")
和 home.lastIndexOf("ee")
都返回 7
。如果JS以ee
为一个单位并返回其索引,为什么不能返回该单位的lastIndexOf?
最佳答案
lastIndexOf
返回子字符串中第一个字符的索引,该子字符串在超字符串中最后出现。
var home = "Home sweet sweet home";
// ^ Matches here
console.log(home.lastIndexOf("ee"));
要查找第二个 e
(当它构成字符串 ee
的一部分时),请使用 indexOf
然后添加 1(您知道第二个字符ee
是子字符串第一个字符之后的 1 个字符,所以您知道要添加那么多,如果您想要子字符串的最后一个字符,那么您可以使用 .length 计算它子字符串的
)。
var home = "Home sweet home";
// ^ Matches here
console.log(home.indexOf("ee") + 1);
要查找第二个 e
(当它可能构成或不构成字符串 ee
的一部分时),请使用 indexOf
查找第一个 >e
,然后再次使用它,传递第一个 e
之后的字符索引作为第二个参数。
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);
关于javascript - JavaScript 中的indexOf 和lastIndexOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40421671/