|
| 1 | +--- |
| 2 | +Title: '.lastIndexOf()' |
| 3 | +Description: 'Returns the index of the last occurrence of a specified substring within a string, or -1 if the substring is not found.' |
| 4 | +Subjects: |
| 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 | +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. |
| 17 | + |
| 18 | +## Syntax |
| 19 | + |
| 20 | +```pseudo |
| 21 | +string.lastIndexOf(searchValue, fromIndex) |
| 22 | +``` |
| 23 | + |
| 24 | +**Parameters:** |
| 25 | + |
| 26 | +- `searchValue`: The substring to search for. |
| 27 | +- `fromIndex` (optional): The position to start searching backward from. Defaults to the string’s length. |
| 28 | + |
| 29 | +**Return value:** |
| 30 | + |
| 31 | +Returns an integer representing the index of the last occurrence of the specified substring within the string. If the substring isn’t found, it returns `-1`. |
| 32 | + |
| 33 | +## Example 1: Finding the Last Mention of a Name |
| 34 | + |
| 35 | +In this example, a chat message contains multiple mentions of a person’s name, and the method finds the last one: |
| 36 | + |
| 37 | +```js |
| 38 | +const message = 'Hey Sam, Sam, are you coming to the meeting, Sam?'; |
| 39 | +const lastSam = message.lastIndexOf('Sam'); |
| 40 | +console.log(lastSam); |
| 41 | +``` |
| 42 | + |
| 43 | +The output of this code is: |
| 44 | + |
| 45 | +```shell |
| 46 | +45 |
| 47 | +``` |
| 48 | + |
| 49 | +## Example 2: Searching Backward from a Certain Point |
| 50 | + |
| 51 | +In this example, the search begins from a specific index to locate the previous occurrence of a keyword: |
| 52 | + |
| 53 | +```js |
| 54 | +const report = 'Error at line 23. Warning at line 45. Error again at line 78.'; |
| 55 | +const prevError = report.lastIndexOf('Error', 40); |
| 56 | +console.log(prevError); |
| 57 | +``` |
| 58 | + |
| 59 | +The output of this code is: |
| 60 | + |
| 61 | +```shell |
| 62 | +38 |
| 63 | +``` |
| 64 | + |
| 65 | +## Codebyte Example: Locating the Last Hashtag in a Social Media Caption |
| 66 | + |
| 67 | +In this example, a caption includes multiple hashtags, and the method identifies the position of the last one: |
| 68 | + |
| 69 | +```codebyte/javascript |
| 70 | +const caption = 'Just finished a 10k run! #fitness #running #motivation'; |
| 71 | +const lastHashtag = caption.lastIndexOf('#'); |
| 72 | +console.log(lastHashtag); |
| 73 | +``` |
0 commit comments