JavaScript string search() method : The search() method is used to search a specific string within a given string. It returns the index of the searched string and if no string matched then it returns the -1.
Syntax of the search() method :
string.search(search-value)
search-value : This is required parameter. This parameter could be a string or a regular expression. The string value internally converted into the regular expression.
Example of search() method: Here I will show you how to use the search() method in JavaScript. The first example will take the simple string parameter and the second example take the regular expression as a parameter which will search the string with case-insensitive.
Example1.html
<!DOCTYPE html>
<html>
<body>
<p>To display the position of string "good", press button.</p>
<button onclick="searchString()">search</button>
<p id="container"></p>
<script>
function searchString() {
var msg = "Good things happens with good people.";
var indx = msg.search("good");
document.getElementById("container").innerHTML = indx;
}
</script>
</body>
</html>
Output : 25
Example2.html
<!DOCTYPE html>
<html>
<body>
<p>To search a string for "good", click the button.</p>
<button onclick="searchString()">search</button>
<p id="container"></p>
<script>
function searchString() {
var str = "Hey! Good things happens with good people.";
var indx = str.search(/good/i);
document.getElementById("container").innerHTML = indx;
}
</script>
</body>
</html>
Output : 5
0 Comment(s)