IndexOf.One string exists as a substring inside another. We can search for it with indexOf or lastIndexOf. An index integer is returned.
Another method,includes, also can search for strings. For more complex requirements a regular expression pattern and search() can be used.
IndexOf example.This method searches strings. We pass it a substring we want to find in a string. It returns the index where the substring is found. If nothing is found it returns -1.Strings
First: We have a string that contains the final 3 letters of the alphabet. Then we search for 2 of them—and "q" which is not found.
Start argument.The indexOf method has an optional second argument. This is an integer that tells indexOf where to start searching.
Here: We pass 0 and the first "cat" string is found. But when we pass 1, we find the second "cat" string as we miss the first.
LastIndexOf.This method searches a string from the right side. It starts with the last index and then processes backwards to the first index.
Includes.Sometimes an index is not needed when searching a string. We use includes() to see whether a substring exists as part of another or not.
Tip: This could be implemented with indexOf and a check against -1. But includes is easier to read.
Scan strings.With indexOf, we must loop over the string to find a single value. This can result in excessive looping. We can scan strings for multiple characters at once with charCodeAt.charCodeAt
Dot Net Perls
|© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, firstname.lastname@example.org.|