Press ESC to close

JavaScript lastIndexOf

0 1333

The JavaScript lastIndexOf method can be used, as well as indexOf, with both arrays and strings. In this lesson we will study it by applying it to strings.

The syntax is therefore the following: string.lastIndexOf (value, start).

The return value is a numeric value that represents the position of the last element’s position in the string, if there is more than one. If it doesn’t find this value, it returns -1.

As with indexOf, the value, i.e. the first argument passed as a parameter, can be a word, a number or a phrase. If more than one occurrence of this value is found, the method always returns the index of the last value found.

Instead the second parameter, beginning, is the starting point to search for the value. In some cases it may be necessary not to start from the beginning of the string. If start is not specified, it starts from position 0.

JavaScript lastIndexOf – examples

We use this method in a first example, where we take a string and search in it for the last occurrence of a word.

Here is a simple example:



var coding = 'Coding is fun and creative. Try coding yourself.';

var indexString = coding.lastIndexOf('coding');
console.log(indexString);

In the browser console we will see as a result 60, that is the position of the last word. If we had used indeOf we would have obtained 5, which is the position of the first word.

If the element to be searched for is not present then the JavaScript lastIndexOf method returns the value -1, so we modify the value to search for in the string, as in the example below:



var coding = 'Coding is fun and creative. Try coding yourself.';

var indexString = coding.lastIndexOf('the coding');
console.log(indexString);

In the browser console we will therefore display the value -1.

In this lesson we studied the use of the JavaScript lastIndexOf method with strings, remember that the same method can also be applied to arrays.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants

Other stories

JavaScript replace

Next Story

JavaScript indexOf

Previous Story