find last occurrence of character in string in javascript

How to Find Last Occurrence of Character in String in Javascript

Javascript provides many useful string functions to work with different string inputs and variables. Sometimes you may need to find last occurrence of character in string in Javascript. You can easily find it with the help of lastIndexOf() function in Javascript. In this article, we will learn how to find last occurrence of character in Javascript.



How to Find Last Occurrence of Character in String in Javascript

LastIndexOf() function returns the position of last occurrence of character or substring in a string. It searches from the end to the beginning and returns the position from first character. If the value is not found, it returns -1. Here is the syntax of lastIndexOf

string.lastIndexOf(searchvalue, start)

In the above command, you need to specify the search value as first argument, and optionally mention the starting position from where you need Javascript to start looking.

Please note, it does a case sensitive search as seen below.

let str = "Hello good morning is good";
str.lastIndexOf("good")   // Returns 22
str.lastIndexOf("Good")   // Returns -1

You can also use it to find last occurrence of character as shown below.


let str = "Hello good morning";
str.lastIndexOf("o")   // Returns 12
str.lastIndexOf("z")   // Returns -1

That’s it. In this short article, we have learnt how to find last occurrence of a character.

Also read:

How to Find Last Occurrence of Character in Python
How to Split Python List into N Sublists
How to Insert Text At Certain Line in Linux
Django Get Unique Value from Queryset
How to Create RPM for Python Module

Leave a Reply

Your email address will not be published. Required fields are marked *