Last Updated : 11 Jul, 2025
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.
string.search( A )Parameters
This method accepts a single parameter A which holds the regular expression as an object.
Return ValueThis 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 JavaScriptThe 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.
// 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));
Example 2: Searching Characters without Regular Expressions in JavaScript JavaScript
let str = "GeeksforGeeks";
let searchString = "for";
let Result = str.search(searchString);
console.log(Result);
Supported Browsers
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4