The JavaScript search() method is used to searches a string for a specified String value and it returns the position of the match.
JavaScript search function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="findString()">Find the position</button>
<p id="sample"></p>
<script>
function findString() {
var str = "i love learnkode";
var result = str.search("learnkode");
document.getElementById("sample").innerHTML = result;
}
</script>
</body>
</html>
JavaScript search function will return 2 if you search love from a string like ""i love learnkode"
JavaScript search function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="findString()">Find the position</button>
<p id="sample"></p>
<script>
function findString() {
var str = "i love learnkode";
var result = str.search(/love/i);
document.getElementById("sample").innerHTML = result;
}
</script>
</body>
</html>