String search() method in JavaScript

You can use the search() in JavaScript to find the 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:

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

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
amazon tools
amazon tools
1 year ago

What’s up, just wanted to mention, I liked this article.
It was inspiring. Keep on posting!