In JavaScript, you can search for a specific substring within a string using the search()
method. The search()
method returns the index of the first occurrence of the specified substring, or -1
if the substring is not found.
Example
string.search(searchvalue)
The searchvalue
parameter is the substring you want to search for within the string
.
example
var str = "Hello world!";
var n = str.search("world");
In this example, the search()
method is used to search for the substring "world"
within the string "Hello world!"
. The variable n
will contain the value 6
, which is the index of the first occurrence of the substring.
If the specified substring is not found within the string, the search()
method will return -1
.
var str = "Hello world!";
var n = str.search("foo");
In this example, the search()
method is used to search for the substring "foo"
within the string "Hello world!"
. Since the substring is not found within the string, the variable n
will contain the value -1
.
It’s important to note that the search()
method is case-sensitive. If you want to perform a case-insensitive search, you can convert both the string and the substring to lowercase or uppercase before performing the search.
var str = "Hello world!";
var n = str.toLowerCase().search("hello");
In this example, the toLowerCase()
method is used to convert the string "Hello world!"
to all lowercase letters before performing the search for the substring "hello"
. Since the search()
method is case-sensitive, this will return the correct index of the first occurrence of the substring.