String search() method in JavaScript

You can use the search() in JavaScript to find index i.e position of the first appearance for the specified string. If the specified string is not found in the main string then it returns -1.


<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
    var str = "Try to find me here. If you failed find me at other places.";
    var index ="find");
    document.write('position of find is: ', index);


position of find is: 7


You may seem like indexOf() and search() methods are the same but they are not same. Difference between these two methods is:
1) the indexOf method cannot accept strong search value like a regular expression.
2) search methods cannot take the second parameter for the starting position.

One Comment

Leave a Reply

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