3 Example(s) of JavaScript search function


Description :

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>

Output

Description :

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>

Output

Description :

JavaScript search function will search for a specified string and return the output "Contains learnkode" if string is matched.


JavaScript search function Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>

 <script type="text/javascript">
  var re = /learnkode/gi;
  var str = "i love learnkode.";
  if (str.search(re) == -1) {
      document.write("Does not contain learnkode" );
  } else {
      document.write("Contains learnkode" );
  }
 </script>
</body>
</html>

Output