Table of contents
- 1. Summary
- 2. Syntax
- 3. Parameters
- 4. Description
- 5. Examples
Summary
Executes the search for a match between a regular expression and this String object.
Method of String | |
|---|---|
| Implemented in | JavaScript 1.2 |
| ECMAScript Edition | ECMAScript 3rd Edition |
Syntax
string.search(regexp)
Parameters
regexp- A regular expression object. If a non-RegExp object
objis passed, it is implicitly converted to a RegExp by usingnew RegExp(obj).
Description
If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1.
When you want to know whether a pattern is found in a string use search (similar to the regular expression test method); for more information (but slower execution) use match (similar to the regular expression exec method).
Prior to Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5)
, search() was implemented incorrectly; when it was called with no parameters or with undefined, it would match against the string "undefined", instead of matching against the empty string. This is fixed; now "a".search() and "a".search(undefined) correctly return 0.
Examples
Example: Using search
The following example prints a message which depends on the success of the test.
function testinput(re, str){
if (str.search(re) != -1)
midstring = " contains ";
else
midstring = " does not contain ";
document.write (str + midstring + re);
}