ArticleDirectory
- Syntax
- Return Value
- Description
- Example 1
- Example 2
Definition and usage
The search () method is used to retrieve the specified substring in a string or a substring that matches a regular expression.
Syntax
Stringobject. Search (Regexp)
| Parameters |
Description |
| Regexp |
This parameter can be a substring to be retrieved in stringobject or a Regexp object to be retrieved. Note: To perform a case-insensitive search, append the flag I. |
Return Value
The starting position of the first substring in stringobject that matches Regexp.
Note:If no matched substring is found,-1 is returned.
Description
The search () method does not perform global match. It ignores the flag. It also ignores the lastindex attribute of Regexp and always searches from the start of the string, which means it always returns the first matching position of stringobject.
Example 1
In this example, we will retrieve "w3school ":
<SCRIPT type = "text/JavaScript"> var STR = "Visit w3school! "Document. Write (Str. Search (/w3school/) </SCRIPT>
Output:
6
In the following example, w3school cannot be retrieved (because search () is case sensitive ).
<SCRIPT type = "text/JavaScript"> var STR = "Visit w3school! "Document. Write (Str. Search (/w3school/) </SCRIPT>
Output:
-1
Example 2
In this example, we will perform a case-insensitive search:
<SCRIPT type = "text/JavaScript"> var STR = "Visit w3school! "Document. Write (Str. Search (/w3school/I) </SCRIPT>
Output:
6