Open In App

JavaScript String search() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The search() method in JavaScript is used to search for a specified substring within a string. It returns the index of the first occurrence of the substring within the string. If the substring is not found, it returns -1.

Syntax:

string.search( A )

Parameters:

This method accepts a single parameter A which holds the regular expression as an object.

Return Value:

This method returns the index of the first match string in between the regular expression and the given string object and returns -1 if no match is found. Indexing starts from zero (0) and in the first attempt, an alphabet is matched, then it does not check further. Simply, it returns the index of that first matched alphabet.

JavaScript String search() Method Examples

Example 1: Searching Characters with Regular Expressions in JavaScript

The code utilizes the search() method with regular expressions to find the index of matching characters within the string “GeeksforGeeks”. It prints the index of the first occurrence of ‘G’, ‘e’, and ‘s’ respectively.

JavaScript
// Taking input a string.
let string = "GeeksforGeeks";

// Taking a regular expression.
let re1 = /G/;
let re2 = /e/;
let re3 = /s/;

// Printing the index of matching alphabets
console.log(string.search(re1));
console.log(string.search(re2));
console.log(string.search(re3));

Output
0
1
4

Example 2: Searching Characters without Regular Expressions in JavaScript

JavaScript
let str = "GeeksforGeeks";
let searchString = "for";
let Result = str.search(searchString);
console.log(Result);

Output
5

We have a complete list of Javascript Strings methods, to check those please go through Javascript String Complete reference article.

Supported Browser:


Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads