Find last occurrence of character or substring in string javascript; Through this tutorial, i am going to show you how to find last occurrence of character or substring in string javascript
JavaScript Find Last Occurrence of Substring in String
You can use the javaScript String.lastIndexOf()
, which is used to find the last occurrence of a character or substring in a string.
Note that:- If the substring
or occurrence character does not found instring
, It returns -1.
Syntax of JavaScript lastIndexOf() Method
The following syntax demonstrates the String.lastIndexOf()
method; as shown below:
string.lastIndexOf(substring, [, startIndex]);
Remember that, this js lastIndexOf()
method searches for the substring backward from the startIndex
. and this startIndex
is an optional parameter.
Note that, if you ignore the startIndex
, the search starts from the end of the given string.
This is a very important for note that, The lastIndexOf()
always perform a case-sensitive search.
Example 1- To find last occurrence of character in string javascript
Now i will take first example usinglastIndexOf()
method to find the last occurrence of a character or substring 'r'
in the string 'programming'
; as shown below:
let str = 'programming'; let index = str.lastIndexOf('r'); console.log(index);
Output:
4
Example 2 – To find last occurrence of character in string with case sensitive in javascript
I will take second example with case sensitive string; as shown below:
let str = 'JavaScript Programming language'; let substr = 's'; let index = str.lastIndexOf(substr); console.log(index); // -1
Conclusion
In this tutorial, you have learned everything about the lastIndexOf()
string method in js with various examples.