The String lastIndexOf() method

By

Learn how the JavaScript lastIndexOf() method returns the position of the last occurrence of a substring inside a string, or -1 when the value is not found.

~~~

lastIndexOf() gives the position of the last occurrence of the string passed as parameter in the current string.

Returns -1 if the search string is not found.

'JavaScript is a great language. Yes I mean JavaScript'.lastIndexOf('Script') //47
'JavaScript'.lastIndexOf('C++') //-1

Also see indexOf().

How is it different from indexOf()?

indexOf() returns the first occurrence, scanning from the start. lastIndexOf() returns the last one:

const sentence = 'JavaScript is a great language. Yes I mean JavaScript'

sentence.indexOf('Script') //4
sentence.lastIndexOf('Script') //47

Notice that even though the search runs backwards, the index you get is counted from the start of the string, like any other string index. lastIndexOf() changes where the search starts, not how positions are measured.

Both methods return the index of the first character of the match, and both are case sensitive:

sentence.lastIndexOf('script') //-1

The lowercase script never appears in the string, so we get -1.

The second parameter

You can pass a second argument, the index where the backwards search starts. Only matches that begin at that position or earlier are considered:

sentence.lastIndexOf('Script', 40) //4

The occurrence at position 47 is past index 40, so it’s skipped, and we get the earlier one at position 4.

One odd input worth knowing: searching for an empty string returns the length of the string, because an empty match “fits” right at the end:

'JavaScript'.lastIndexOf('') //10

A real-world use

The classic job for lastIndexOf() is grabbing a file extension. A file name can contain multiple dots, and only the last one starts the extension:

const file = 'holiday.photo.jpg'
file.slice(file.lastIndexOf('.') + 1) //'jpg'

indexOf() would find the dot after holiday and give you 'photo.jpg'. Searching from the end gets the right one.

Be careful with names that have no dot at all:

const file = 'README'
file.slice(file.lastIndexOf('.') + 1) //'README'

lastIndexOf('.') returns -1, so slice(-1 + 1) is slice(0), which returns the whole string. It looks like it works, until a file without an extension comes along. Check for -1 first:

const dot = file.lastIndexOf('.')
const extension = dot === -1 ? '' : file.slice(dot + 1)
~~~

Related posts about js: