JavaScript String indexOf(): Find Occurrence Position in String

JavaScript find the first occurrence of a character position in the string; This tutorial will guide you on how to find first occurrence of a character position in the string using the javascript string indexOf() method.

In this tutorial, you also learn javascript to find the occurrence of the character in the string.

JavaScript String indexOf() Method

The javascript string method indexOf() is used to find the first occurrence of a character position in given string.

Note:- This string method returns -1 if the value to search is not found in the given string.

Syntax:-

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

str.indexOf( search_value, start)

Here,

  • 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

Ex1:-

Let’s take the first example of indexOf() method in javascript. Let you have one string like “Hello developers, welcome to the javascript tutorial.”. In this string, you want to find the first “de” character. Let’s see the below example:

var string = "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

Ex2:-

Now take a second example with a specific position. Let you have one string like above. And you want to find string or characters in a given string with a specific position. Let’s see the below-given example:

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

Result of the above code is:-44

Recommended JavaScript Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *