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
with str2
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 index position
- 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 index position
- position is optional, the default value is
string.length
- if string doesn't contain
substring
, returns -1
Let's take a look at these methods one by one. The replace()
method replaces the first occurrence of 'A' with 'Z'. This is why the new string starts with 'Z' instead of 'A'. The search()
method searches for the first occurrence of 'A' using regular expression and prints the index, which is why 0 is printed to the console. The indexOf()
method returns the index of the first occurrence of 'B' starting from the left, which is why 1 is printed to the console. The lastIndexOf
method return the index of the last occurrence of 'B', which is why 21 is printed to the console.
Edit Me on GitHub!