JavaScript String indexOf() method

The indexOf method in JavaScript is utilized to locate the position of a specific character or substring within a sequence of characters. It is important to note that this method is case-sensitive.

The index of the initial character in a string always begins at zero. If a character is absent from the string, the function returns -1.

Syntax

The subsequent techniques are employed to locate the position of a specific element.

Method Description
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 - This signifies the individual character that you are looking for, such as 'a'.

index - It signifies the starting index position from which the search initiates.

str - This denotes the string that you are looking for, such as "Java".

Return

Index of a particular character.

JavaScript String indexOf method example

Let us explore the different methods to locate the position of an element through straightforward examples.

Example 1

In this section, we will display the location of an individual character.

Example

<script>

var web="Learn JavaScript on Example";

document.write(web.indexOf('a'));

</script>

Output:

Example 2

In this illustration, we will specify the index position from which the search will commence.

Example

<script>

var web="Learn JavaScript on Example";

document.write(web.indexOf('a',3));

</script>

Output:

Example 3

In this section, we will display the index of the initial character in a given string.

Example

<script>

var web="Learn JavaScript on Example";

document.write(web.indexOf("Java"));

</script>

Output:

Example 4

In this instance, we will specify the index position from which the search will commence.

Example

</script>

var web="Learn JavaScript on Example";

document.write(web.indexOf("Java",7));

</script>

Output:

Example 5

In this section, we will attempt to locate the element by altering its case sensitivity.

Example

<script>

var web="Learn JavaScript on Example";

document.write(web.indexOf("java"));

</script>

Output:

Input Required

This code uses input(). Please provide values below: