Hello, code adventurer! Today, we're navigating the complexities of JavaScript's Search and Replace functionality. This functionality enables us to find and replace words within sentences. Let's set sail!
Our journey begins with three primary tools that we can use to locate words within a string: indexOf(), lastIndexOf(), and includes(). Let's start with indexOf first!
The indexOf() function marks the first instance of a provided word within a provided string. Remember, like a puzzle, string positions start at 0. It's the finding function within our string universe. When there is no occurrence of the provided word, indexOf returns -1.
The code above searches for the word "Planet" within the spaceMessage string and reports its first location — the seventh position. When we search for "Planet Mars", which doesn't exist, it returns -1.
To find the last occurrence of a word, we have lastIndexOf(). It starts the search from the end of the string, which proves practical when a word appears more than once. When there is no single occurrence of the provided word, the method returns -1, similarly to indexOf.
In this example, "Planet" appears twice in the spaceMessage string, but lastIndexOf() tells us the position of the last occurrence — 21. "Planet Mars" doesn't occur in spaceMessage at all, so the result is -1.
Our next guiding star, includes(), verifies the existence of a word in a string. It returns true if the word nests in the string and false if not.
The output true confirms that "Planet" indeed exists in spaceMessage. The output false confirms "Planet Mars" doesn't exist in spaceMessage.
