JavaScript String indexOf() method

The indexOf() method in JavaScript is used to search a string for a specified substring, 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 indexOf() method returns the index at which the substring was found. If the substring is not found, the indexOf() method returns -1.

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

const string1 = 'Hello, world!';

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

// the result will be: 7

In the code example above, we first declare a string called string1 that contains the text Hello, world!. We then use the indexOf() method to search the string1 string for the substring world. The indexOf() 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 indexOf() method.

As a result of calling the indexOf() method, the result variable will be set to 7, which is the index at which the substring world was found in the string1 string. If the string1 string did not contain the substring world, the result variable would be set to -1.

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: