JavaScript String search() Method

The search function in JavaScript is utilized for finding a regular expression within a specified string. In cases where no match is found, this function will return -1.

Syntax

The syntax representing the search method is as follows:

Example

string.search(regexp)

Parameter

The term "regexp" is used to denote the regular expression that will be utilized for searching.

Return

The position of searched character.

JavaScript String search Method Example

Let's see some examples of search method.

Example 1

Let's consider a basic illustration demonstrating how to locate a specific string.

Example

<script>

var str="JavaScript is a scripting language. Scripting languages are often interpreted";

document.writeln(str.search("scripting"));

</script>

Output:

Example 2

In this instance, we will observe that the search function is sensitive to letter case.

Example

<script>

var str="JavaScript is a scripting language. Scripting languages are often interpreted";

document.writeln(str.search(/Scripting/)); 

</script>

Output:

Example 3

To disregard the case sensitivity of the search method, we can utilize the ignore flag. This can be exemplified through the following example:

Example

<script>

var str="JavaScript is a scripting language. Scripting languages are often interpreted";

document.writeln(str.search(/Scripting/i));

</script>

Output:

Example 4

In this instance, we will demonstrate how to search for a regular expression that is absent in the provided string.

Example

<script>

var str="JavaScript is a scripting language. Scripting languages are often interpreted";

document.writeln(str.search(/example/));

</script>

Output:

Input Required

This code uses input(). Please provide values below: