JavaScript search() method
The search()
method in JavaScript is used to search for a specified substring or pattern within a string. It returns the index of the first match of the given regular expression (or substring) within the string. If no match is found, it returns -1
.
Syntax:
regexp
: A regular expression (RegExp object) or a string that specifies the pattern to search for in the string. If a string is provided, it is treated as a regular expression without any flags.
Return Value:
- Returns the index of the first match of the regular expression within the string.
- If no match is found, it returns
-1
.
Example 1: Basic Usage
In this example, the method returns 7
, which is the index of the substring "World"
in the string "Hello, World!"
.
Example 2: Case Sensitivity
The search()
method is case-sensitive. It will only find matches that exactly match the case of the search string.
Here, searching for "world"
(lowercase) returns -1
because it does not match the uppercase "World"
.
Example 3: Using Regular Expressions
You can use a regular expression to define a more complex search pattern.
In this example, the regular expression /ain/
matches the first occurrence of the substring "ain"
and returns its index, which is 5
.
Example 4: Using Flags with Regular Expressions
You can also use flags with regular expressions to modify the search behavior.
In this case, the i
flag makes the search case-insensitive, allowing it to match "AIN"
regardless of case.
Example 5: No Matches
If the pattern is not found in the string, the method returns -1
.
Here, the search for the substring "JavaScript"
returns -1
because it is not present in the string.
Example 6: Search with Dynamic Patterns
You can use variables to create dynamic search patterns, which can be particularly useful in applications where the search term is user-generated.
In this example, the variable searchTerm
is used to create a regular expression dynamically, allowing for flexible searching.
Summary:
- The
search()
method is used to find the index of the first occurrence of a substring or pattern in a string. - It takes a regular expression or a string as the search value.
- It returns the index of the first match or
-1
if no match is found. - The method is case-sensitive unless a case-insensitive flag is used with a regular expression.
- It can be used with dynamic patterns by creating RegExp objects from variables.