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.

Example:

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

Output:

position of find is: 7

**Note:

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