Latest

recent

JavaScript search() Method

Definition and Usage

The search() method is used to search a string for a specified value.
This method supports regular expressions. You can learn about the RegExp object in our JavaScript tutorial.

Syntax

stringObject.search(searchstring)

Parameter Description
searchstring Required. The value to search for in a string. To perform a case-insensitive search add an 'i' flag


Tips and Notes

Note: search() is case sensitive.
Note: The search() method returns the position of the specified value in the string. If no match was found it returns -1.

Example 1 - Standard Search

In the following example we will search for the word "Potter":
<script type="text/javascript">
var str="Harry Potter";
document.write(str.search(/Potter/));
</script>

The output of the code above will be:

6

Note: In the following example the word "Potter" will not be found (because the search() method is case sensitive):

<script type="text/javascript">
var str="Harry Potter!";
document.write(str.search(/potter/));
</script>

The output of the code above will be:

-1


Example 2 - Case-insensitive Search

In the following example we will perform a case-insensitive search:

<script type="text/javascript">
var str="Harry Potter";
document.write(str.search(/potter/i));
</script>

The output of the code above will be:

6
JavaScript search() Method Reviewed by 1000sourcecodes on 21:35 Rating: 5
Powered by Blogger.