JavaScript String indexOf() method

The JavaScript string indexOf() method is used to search the position of a particular character or string in a sequence of given char values. This method is case-sensitive.

The index position of first character in a string is always starts with zero. If an element is not present in a string, it returns -1.

Syntax

These are the following methods used to search the position of an element.

MethodDescription
indexOf(ch)It returns the index position of char value passed with method.
indexOf(ch,index)It start searching the element from the provided index value and then returns the index position of specified char value.
indexOf(str)It returns the index position of first character of string passed with method.
indexOf(str,index)It start searching the element from the provided index value and then returns the index position of first character of string.

Parameters

ch - It represent the single character to search like 'a'.

index - It represent the index position from where search starts.

str - It represent the string to search like "Java".

Return

Index of a particular character.

JavaScript String indexOf() method example

Let's see the various ways of searching the position of an element with help of simple examples.

Example 1

Here, we will print the position of a single character.

Test it Now

Output:

2

Example 2

In this example, we will provide the index value from where the search starts.

Test it Now

Output:

7

Example 3

Here, we will print the position of a first character of string.

Test it Now

Output:

6

Example 4

In this example, we will provide the index value from where the search starts.

Test it Now

Output:

20

Example 5

Here, we will try to search the element by changing its case-sensitivity.

Test it Now

Output:

-1





Latest Courses