Open In App

JavaScript String indexOf() Method

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The indexOf() method in JavaScript is used to find the index of the first occurrence of a specified value within a string. The method returns a 0-based index, making it a fundamental JavaScript string manipulation way.

The JavaScript indexOf() method helps locate a substring within a string and returns its position. This method is case-sensitive, meaning that "Hello".indexOf("hello") will return -1 due to the mismatch in the case.

Syntax

str.indexOf(searchValue , index);

Parameters

  • searchValue: The searchValue is the string to be searched in the base string. 
  • index: The index defines the starting index from where the search value will be searched in the base string.

Return value

  • If the searchValue is found, the method returns the index of its first occurrence.
  • If the searchValue is not found, the method returns -1.

Example 1: Finding the First Occurrence of a Substring

Here’s a simple example that finds the position of a substring within a string:

JavaScript
// Original string
let str = 'Departed Train';

// Finding index of occurrence of 'Train'
let index = str.indexOf('Train');
console.log(index);

Output
9

Example 2: Using indexOf() to Locate Substrings

The indexOf() method can be used to search for longer substrings:

JavaScript
// JavaScript to illustrate indexOf() method

// Original string
let str = 'Departed Train';

// Finding index of occurrence of 'Train'
let index = str.indexOf('ed Tr');

console.log(index);

Output
6

Example 3: Handling Case Sensitivity in indexOf() Method

The indexOf() method is case-sensitive. If the cases don’t match, the method will return -1:

JavaScript
// Original string
let str = 'Departed Train';

// Finding index of occurrence of 'Train'
let index = str.indexOf('train');

console.log(index);

Output
-1

Example 4: Using an Index to Start the Search

You can specify a starting index from where the search begins. This is useful when you want to skip certain parts of the string:

JavaScript
// Original string
let str = 'Departed Train before another Train';

// Finding index of occurrence of 'Train'
let index = str.indexOf('Train');

console.log(index);

Output
9

Supported browsers

  • Chrome 1
  • Edge 12
  • Firefox 1
  • Opera 3
  • Safari 1

JavaScript String indexOf() Method
Visit Course explore course icon
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy