JavaScript Search

The search() method searches for a match between a regular expression and a string. This method returns the position of the match, or -1 if no match is found.

Syntax

string.search(regexp)

Let’s see small example,

<script language="javascript">
function findmatch()
{
var myKey = "web development";
var myStringVar = 'You can learn web development things here';
var myMatch = myStringVar.search(myKey);
if(myMatch != -1)
{
alert("There was a match at position " +myMatch);
}
else
{
alert('There was no match');
}
}
</script>
<body>
<input type="button" value="Find match" onClick="javascript:findmatch();">
</body>

Output of the above code will be

There was a match at position 14

In the above example the search pattern is “web development“. The search function then used this name to see if “web development” existed in myStringVar. A match was found, and the position of the match (14), was returned.

Demo

Posted in Javascript