Introduction to JavaScript Search tutorial
The search () method retrieves the substring specified in the string, or retrieves a substring that matches the regular expression.
Grammar
Stringobject.search (regexp) parameter description
RegExp This parameter can be a substring that needs to be retrieved in Stringobject, or it can be a RegExp object that needs to be retrieved.
Note: To perform a retrieval that ignores case, append flag I.
return value
The starting position of the first substring in the stringobject that matches the regexp.
Note: If no matching substring is found, return-1.
Description
The search () method does not perform a global match, and it ignores flag g. It ignores the RegExp lastindex property at the same time and always retrieves it from the beginning of the string, which means it always returns the first matching position of Stringobject.
Instance
Example 1
In this case, we'll retrieve the "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 case, we will perform a retrieval that ignores case:
<script type= "Text/javascript" >
var str= "Visit w3school!"
document.write (Str.search (/w3school/i))
</script> output:
6