There are many methods that can be utilized when searching a string. Each method has different use case and most of them have different parameters. The methods are replace()
, search()
, indexOf()
, and lastIndexOf()
. The syntax and the functions of the methods are shown below.
string.replace(str1, str2)
- replaces first occurrence of
str1
withstr2
string.search(regex)
- searches for a substring based on regular expression (you will learn about this later)
string.indexOf(substring,position)
- returns the left-most occurrence of
substring
in a string after the indexposition
- position is optional and has default value of
0
- if string doesn't contain
substring
, returns-1
string.lastIndexOf(substring,position)
- returns the right-most occurrence of
substring
in a string before the indexposition
- position is optional, the default value is
string.length
- if string doesn't contain
substring
, returns-1