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.


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 =;
if(myMatch != -1)
alert("There was a match at position " +myMatch);
alert('There was no match');
<input type="button" value="Find match" onClick="javascript:findmatch();">

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.


Posted in Javascript