JavaScript String indexOf() Method – Find Substring Position in String

To find the position of the first occurrence of a substring or characters in a string javaScript; Through this tutorial, i am going to show you how to find the position of the first occurrence of a substring or characters in a given string using the javascript string indexOf() method.

If you are searching how do you find the position of a character in a string in javaScript; So you are in right place. In this tutorial, i will take 2 examples of how to find the position of occurrence in string in javascript.

JavaScript String indexOf() Method

The javaScript indexOf() method returns the position of the first occurrence of substring in a string. The indexOf() method returns -1 if the value is not found.

Syntax of JavaScript String indexOf() Method

The basic syntax of js string indexOf() method is:

str.indexOf( search_value, start)

Explanation of above syntax are:

  • Str:- It’s a given string
  • search_value:- This is a required parameter. String to search in a given string
  • start:- This is an optional parameter. Where to start the search in a given string

Example 1 – How to find first occurrence of a character in a string javascript

var string_val = "Hello developers, welcome to the javascript tutorial.";
var res = string.indexOf("de");
document.write('Result of the above code is:-' + res);

Result of the above code is :-6

In this example, have declared a variable called string_val that is assigned the string value of ‘Hello developers, welcome to the javascript tutorial.’. Then invoked the indexOf() method of the string_val variable to look for a substring  within string_val.

Example 2 – How to find or get the position of a character in a string in JavaScript

var test_string = 'Welcome to Laratutorials.com';

console.log(totn_string.indexOf('t'));

Result of the above code is:- 8

In this example, have declared a variable called test_string that is assigned the string value of ‘Welcome to Laratutorials.com.’. Then invoked the indexOf() method of the test_string variable to look for a substring  within string_val.

Recommended JavaScript Tutorials

Leave a Comment