Sometimes we need to find last position of a substring into a string. Substring may be a character or a part of a string. Javascript provide us a very simple method :
lastIndexOf() :
1 | string.lastIndexOf(searchvalue,start) |
searchvalue Required. The string to search for
start Optional. The position where to start the search (searching backwards). If omitted, the default value is the length of the string
Return type : number
The lastIndexOf() method returns the position of the last occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Example: Search a string for "best" <script> var str = "Hello best world, this is best in the world."; var pos = str.lastIndexOf("best"); if(pos > -1) alert('Found'); else alert('Not found'); </script> The result of pos will be: 26 |
Note:
1. The lastIndexOf() method is case sensitive.
2. It returns position starting from 0 index.
3. It is supported in all major browsers.
See : indexOf()
More Examples:
1 2 3 4 5 6 7 8 9 10 11 | Examples: Find the last occurrence of the letter "best" in a string: <script> var str = "Hello best world, this is best in the world of enjoy."; var pos = str.lastIndexOf("best"); </script> The result of pos will be: 26 |
1 2 3 4 5 6 7 8 9 10 11 | Example: Find the last occurrence of the letter "best" in a string, starting the search at position 20: <script> var str = "Hello best world, this is best in the world."; var pos = str.lastIndexOf("best",20); </script> The result of pos will be: 6 |
Like this, we can find the position of a substring occurrence in the string.