JavaScript String search() Method - JavaScript Tutorial

JavaScript String search() Method

BLUF: This tutorial on JavaScript String search() Method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript String search() Method

Understanding JavaScript String search() Method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience