Press ESC to close

JavaScript indexOf

0 1466

The JavaScript indexOf method can be used with both arrays and strings. indexOf in this lesson is applied to strings.

The syntax of this JavaScript method is therefore the following: string.indexOf (value, start).

Returns a numeric value that represents the position of the element in the string. If it doesn’t find the value, it returns -1.

In particular, the string represents where to look for the value. Where the value, that is the first argument passed as a parameter, can be a word, a number or a sentence. If more than one occurrence of this value is found, the method still returns the index of the first value found.

The second parameter, beginning, represents the starting point to carry out the search, as in some cases it may be necessary not to start from the beginning. If not specified, it starts from 0.

JavaScript indexOf – examples

Let’s take a simple example of using this method.

We create a sentence and through the indexOf method we search for the word thought, for example.



var coding = 'Programming helps the development of logical thinking, let's have fun learning JavaScript';

var indexString = coding.indexOf('thought');
console.log(indexString);

As a result in the console we will find the value 34 which indicates the position of the word thought.

For example, if the sentence were to contain the word thought several times, it would always give position 34.

We said that if it does not find the element, the indexOf method in JavaScript returns the value -1, so let’s try to change the value to search for in the string, as in the example below:



var coding = 'Programming helps the development of logical thinking, let's have fun learning JavaScript';

var indexString = coding.indexOf('thought');
console.log(indexString);

So in this case in the console we will see as a result -1 as the value passed as argument is not contained in the string.

In this lesson we studied the use of the JavaScript indexOf method with strings, the same method can be applied to arrays, as we will see in this lesson: indexOf with 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 lastIndexOf

Next Story

JavaScript split

Previous Story