JS: indexOf() Method

The JavaScript string has some of the properties of array. You may access a character of the string using index.

In order to find the correct index of a character , you can use indexOf() method of string class.

Here is an example program to demonstrate the usage of this method.

<!DOCTYPE html>
   <title>JS: indexOf Method</title>
   <meta charset="utf-8">
var answer = "Lion is the king of Jungle!";
var res = answer.indexOf('king');
//output = 12

The above program will result in 12. The array or string index always start at 0 in JavaScript programming.

The substring ‘king’ starts at index 12. The script goes through all the characters one-by-one and finally reaches the character ‘k’ which is at index 12.

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag