React with Redux Certification Training
- 5k Enrolled Learners
- Live Class
IndexOf function is used to find out the index of an element in a String and an Array. There are two variations, one is indexOf that is used to give you the position of search element or the first matched element:
If element is not found it will return -1.
The second one is lastIndexOf function which is used to find the element from the last in a string or in an array.
var string =’Welcome to Edureka’ string.indexOf(‘Welcome’)
For the lastIndexof function, we can take the following example:
var = ‘Welcome to edureka’ string.lastIndexOf(‘edureka’)
The str.indexOf() function finds the index of the first occurrence of the argument string in the given string. The value returned is 0-based. Also, it returns -1 if the value to search for never occurs.
The first argument, searchValue is the string that is to be searched in the base string. The second argument to the function index defines the starting index from where the searchValue is to be searched in the base string.
This function returns the index of the string (0-based) where the searchValue is found for the first time. If the searchValue cannot be found in the string then the function returns -1.
var str = "Hello, welcome to edureka!"; var n = str.indexOf("e");
The arr.indexOf() function is used to find the index of the first occurrence of the search element provided as the argument to the function.
The first argument, searchElement is the value to be searched in the array. The second argument to this function is the optional index argument which defines the starting index in the array from where the element is to be searched. If this argument is not provided then index 0 is taken as the starting index to begin the search as it is the default value.
This function returns the index of the first occurrence of the searchElement. If the element cannot be found in the array, then this function returns -1.
var cars = ["BMW", "Audi", "Ferrari"]; var arr = cars.indexOf("Ferrari");
Both the indexOf() and search() methods are used to check whether a substring exists in the string or not. Also, it returns either of the indexes of the substring or -1 if the substring does not exist in the string. But there is a difference between indexOf() and search() methods. Let’s have a look at the syntax of the two methods.
Syntax of indexOf() method:
Syntax of search() method:
Now, you can see that in indexOf() method, there is an optional parameter(offset) from where we can start the searching but the method search() does not have this feature. It simply takes the substring and starts searching from the 0th index.
Check out our Full Stack Web Developer Masters Program which comes with instructor-led live training and real-life project experience. This training makes you proficient in skills to work with back-end and front-end web technologies. It includes training on Web Development, jQuery, Angular, NodeJS, ExpressJS, and MongoDB.