Home »
JavaScript
Difference between indexOf() and search() methods in JavaScript
JavaScript indexOf() and search() methods difference: Here, we are going to learn about the difference between indexOf() and search() methods in JavaScript.
Submitted by IncludeHelp, on February 02, 2019
Prerequisites
JavaScript - indexOf() and search() methods
Though indexOf() and search() both methods are used to check whether a substring exists in the string or not and returns either of the index of the substring or -1 (if substring does not exist in the string), there is a difference between indexOf() and search() methods. Consider the syntaxes of both methods:
Syntax of indexOf() method
String.indexOf(substring, [offset]);
Syntax of search() method
String.search(substring);
Difference between indexOf() and search() methods in JavaScript
Now, you can clearly 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.
Example demonstrating the difference between indexOf() and search() methods in JavaScript
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
var str = "friends say Hello";
var substr = "Hello";
var index = str.indexOf(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
var substr = "Hello";
var index = str.search(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
substr = "Hi";
index = str.indexOf(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
substr = "Hi";
index = str.search(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
</script>
</body>
</html>
Output
Hello found at 12 position.
Hello found at 12 position.
Hi does not exist in the friends say Hello.
Hi does not exist in the friends say Hello.
JavaScript String Object Methods »