Question 5
Question
Explain the difference between indexOf()
, includes()
, and search()
methods for string manipulation.
Answer
1. indexOf(searchString, start)
Purpose: Finds the first occurrence of a substring (
searchString
) within a given string.Return Value: Returns the index (position) of the first occurrence of
searchString
. If not found, it returns-1
.start
Parameter (optional): Allows you to specify where to start searching within the string.
2. includes(searchString, start)
Purpose: Checks if a string (
searchString
) exists anywhere within another string.Return Value: Returns
true
if the substring is found, andfalse
otherwise.start
Parameter (optional): Similar toindexOf()
, it lets you control the search starting point.
3. search(regexp)
Purpose: Searches for a regular expression (
regexp
) within a string. This method provides the most powerful and flexible pattern matching capabilities.Return Value: Returns the index of the first match found, or
-1
if no match is found.
Last updated