by Dinesh Thakur Category: Javascript String

JavaScript String search() Method: Whenever working with a strings, sometimes we need to determine if a string contains some specific substring, and if it does, you need to determine where in the string that substring occurs.

The JavaScript search() Method executes the search for a match between a regular expression and a specified string. If a match is found, it returns the position in the string where the beginning of the match was found. Otherwise, it returns –1.

Syntax for JavaScript String search() Method is:

For instance, if you have the string “I am Ironman!” and you search for the substring “Iron”, you want to know that the string contains “Iron” but also where “Iron” occurs. You can perform this type of search with the JavaScript search() Method of the string object.

To perform this search is simple. If “I am Ironman!” is stored in the variable mystring, you would search for “Iron” with the JavaScript search() Method:"Iron");

JavaScript search() Method returns a numeric value indicating the position in the string where it found “is”. In this case, that position is 5.

The following task searches for a substring in another string stored in a variable and displays the position where that substring is found:

1. Open a new HTML document in your preferred HTML or text editor.

2. Create the body of the document with opening and closing body tags:



3. Insert a script block in the body of the document:

<script language="JavaScript">



4. Create a variable named mystring and assign the value “I am Ironman!” to it:

var mystring = "I am Ironman!";

Display the results of the JavaScript search() Method so that the final page looks like

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

" ">

<html xmlns="" xml:lang="en" lang="en">
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <title>JavaScript Search() method </title>
<h1 style="color: blue"> JavaScript search() Method</h1> <hr />
<script type="text/javascript">
    var mystring = "I am Ironman!";
    var tomatch = /Iron/;
      if ( {
       window.alert("Iron found at position ""!"); }
     else { window.alert("Sorry, no Iron in your string."); }

Save the file and close it.

5. Open the file in a browser. You should see the number 5 displayed in the browser as in Figure

JavaScript search() Method

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.