Skip to content

Commit 18a1c1d

Browse files
[Term Entry] JavaScript Strings: lastIndexOf()
1 parent 10578df commit 18a1c1d

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
Title: '.lastIndexOf()'
2+
Description: 'Returns the index of the last occurrence of a specified substring within a string, or -1 if the substring is not found.'
3+
Subjects:
4+
5+
- 'Computer Science'
6+
- 'Web Development'
7+
Tags:
8+
- 'Strings'
9+
- 'Methods'
10+
- 'JavaScript'
11+
CatalogContent:
12+
- 'learn-javascript'
13+
- 'paths/web-development'
14+
15+
---
16+
17+
The **`.lastIndexOf()`** method in JavaScript returns the position of the last occurrence of a specified substring within a [string](https://www.codecademy.com/resources/docs/javascript/strings). If the substring is not found, it returns `-1`. It performs a case-sensitive search and can take an optional starting position from which to begin the search backwards.
18+
19+
## Syntax
20+
21+
```pseudo
22+
string.lastIndexOf(searchValue, fromIndex)
23+
```
24+
25+
**Parameters:**
26+
27+
- `searchValue`: The substring to search for.
28+
- `fromIndex` (optional): The position to start searching backward from. Defaults to the string’s length.
29+
30+
## Example 1: Finding the Last Mention of a Name
31+
32+
In this example, a chat message contains multiple mentions of a person’s name, and the method finds the last one:
33+
34+
```js
35+
const message = 'Hey Sam, Sam, are you coming to the meeting, Sam?';
36+
const lastSam = message.lastIndexOf('Sam');
37+
console.log(lastSam);
38+
```
39+
40+
The output of this code is:
41+
42+
```shell
43+
45
44+
```
45+
46+
## Example 2: Searching Backward from a Certain Point
47+
48+
In this example, the search begins from a specific index to locate the previous occurrence of a keyword:
49+
50+
```js
51+
const report = 'Error at line 23. Warning at line 45. Error again at line 78.';
52+
const prevError = report.lastIndexOf('Error', 40);
53+
console.log(prevError);
54+
```
55+
56+
The output of this code is:
57+
58+
```shell
59+
0
60+
```
61+
62+
## Codebyte Example: Locating the Last Hashtag in a Social Media Caption
63+
64+
In this example, a caption includes multiple hashtags, and the method identifies the position of the last one:
65+
66+
```codebyte/javascript
67+
const caption = 'Just finished a 10k run! #fitness #running #motivation';
68+
const lastHashtag = caption.lastIndexOf('#');
69+
console.log(lastHashtag);
70+
```

0 commit comments

Comments
 (0)