JavaScript String lastIndexOf() method

The lastIndexOf() method in JavaScript is used to search a string for a specified substring, starting from the end of the string, and return the position of the substring within the string. This method takes a single argument, which is the substring to search for in the string. If the substring is found, the lastIndexOf() method returns the index at which the substring was found. If the substring is not found, the lastIndexOf() method returns -1.

Here is an example of how the lastIndexOf() method works:

const string1 = 'Hello, world! Hello, world!';

const result = string1.lastIndexOf('world');

// the result will be: 20

In the code example above, we first declare a string called string1 that contains the text Hello, world! Hello, world!. We then use the lastIndexOf() method to search the string1 string for the substring world, starting from the end of the string. The lastIndexOf() method takes a single argument, which is the substring to search for in the string. In this case, we pass in the string world as the argument to the lastIndexOf() method.

As a result of calling the lastIndexOf() method, the result variable will be set to 20, which is the index at which the last occurrence of the substring world was found in the string1 string. If the string1 string did not contain the substring `

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: