String.prototype.lastIndexOf()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2015ë 7ì.
lastIndexOf() ë©ìëë 주ì´ì§ ê°ê³¼ ì¼ì¹íë ë¶ë¶ì fromIndexë¡ë¶í° ììì¼ë¡ íìíì¬, ìµì´ë¡ ë§ì£¼ì¹ë ì¸ë±ì¤ë¥¼ ë°íí©ëë¤. ì¼ì¹íë ë¶ë¶ì ì°¾ì ì ìì¼ë©´ -1ì ë°íí©ëë¤.
ìëí´ ë³´ê¸°
const paragraph = "I think Ruth's dog is cuter than your dog!";
const searchTerm = "dog";
console.log(
`Index of the last ${searchTerm} is ${paragraph.lastIndexOf(searchTerm)}`,
);
// Expected output: "Index of the last "dog" is 38"
구문
str.lastIndexOf(searchValue[, fromIndex])
매ê°ë³ì
searchValue-
íìí 문ìì´. ë¹ ê°ì ì ê³µí ê²½ì°
fromIndex를 ë°íí©ëë¤. fromIndexOptional-
íìì ììì ì¼ë¡ ì¬ì©í ì¸ë±ì¤. 기본ê°ì
+Infinityì ëë¤.fromIndex >= str.lengthì¸ ê²½ì° ëª¨ë 문ìì´ì íìí©ëë¤.fromIndex < 0ì¸ ê²½ì°ì0ì ì§ì í ê²ê³¼ ëì¼í©ëë¤.
ë°í ê°
문ìì´ ë´ìì searchValueê° ë§ì§ë§ì¼ë¡ ë±ì¥íë ì¸ë±ì¤. ë±ì¥íì§ ìì¼ë©´ -1.
ì¤ëª
문ìì´ì 문ìë ì¼ìª½ìì ì¤ë¥¸ìª½ì¼ë¡ ì¸ë±ì¤ë¥¼ 매ê¹ëë¤. 첫 ë²ì§¸ 문ìì ì¸ë±ì¤ë 0ì´ë©°, ë§ì§ë§ 문ìì ì¸ë±ì¤ë str.length -1ì
ëë¤.
"canal".lastIndexOf("a"); // 3 ë°í
"canal".lastIndexOf("a", 2); // 1 ë°í
"canal".lastIndexOf("a", 0); // -1 ë°í
"canal".lastIndexOf("x"); // -1 ë°í
"canal".lastIndexOf("c", -5); // 0 ë°í
"canal".lastIndexOf("c", 0); // 0 ë°í
"canal".lastIndexOf(""); // 5 ë°í
"canal".lastIndexOf("", 2); // 2 ë°í
ì°¸ê³ :
'abab'.lastIndexOf('ab', 2)ë 0ì´ ìëê³ 2를 ë°íí©ëë¤. fromIndexë íìì ììì ë§ ì íí기 ë문ì
ëë¤.
ëì문ì 구ë¶
lastIndexOf() ë©ìëë ëì문ì를 구ë¶í©ëë¤. ì를 ë¤ì´, ìë ìì ë -1ì ë°íí©ëë¤.
"Blue Whale, Killer Whale".lastIndexOf("blue"); // -1 ë°í
ìì
>indexOf()ì lastIndexOf() ì¬ì©í기
ìë ìì ë 문ìì´ "Brave new world" ë´ìì í¹ì ê°ì ìì¹ë¥¼ íì¸í기 ìí´ indexOf()ì lastIndexOf()를 ì¬ì©í©ëë¤.
let anyString = "Brave new world";
console.log("ììì ì¼ë¡ë¶í° ì²ì ë§ëë wì ìì¹ë " + anyString.indexOf("w"));
// logs 8
console.log(
"ëì ì¼ë¡ë¶í° ì²ì ë§ëë wì ìì¹ë " + anyString.lastIndexOf("w"),
);
// logs 10
console.log(
'ììì ì¼ë¡ë¶í° ì²ì ë§ëë "new"ì ìì¹ë ' + anyString.indexOf("new"),
);
// logs 6
console.log(
'ëì ì¼ë¡ë¶í° ì²ì ë§ëë "new"ì ìì¹ë ' + anyString.lastIndexOf("new"),
);
// logs 6
ëª ì¸
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-string.prototype.lastindexof> |