For this week’s #FunctionFriday, I’m going to cover 3 more string functions. This group is related to searching for a particular block of text within a string: indexOf, lastIndexOf, and nthIndexOf.
All three of these functions work pretty much the same way. You pass in the text you are searching for and the text you are searching within, and it tells you whether or not if found a match. Let’s start with the base function: indexOf.
The pattern for indexOf is pretty simple:
If the function finds the text you are looking for, it returns the position (remember it’s 0-based) of the first match it finds. It doesn’t let you know if there is more than one match. It only cares about the first one. If it doesn’t find any matches, it returns a value of -1.
As an example:
indexOf('Frank', 'Hello there, Frank. How are you doing, Frank?')
returns a value of 13, the position of the first mention of “Frank”.
This works exactly the same as the indexOf function, except it starts from the end and works towards the front. The pattern is:
Again, if the function finds a match, it returns the position of the last match in the string. If no match is found, a value of -1 is returned. In our example from above:
lastIndexOf('Frank', 'Hello there, Frank. How are you doing, Frank?')
returns a value of 39, the position of the last “Frank”.
This function works similarly to the other two, but it takes a third parameter in the function call.
nthIndexOf('<textToSearchFor>', '<textToSearchIn>', '<occurence>')
The value of occurrence is the instance of the string you’re searching for. For example, if you want the second occurrence of a value, pass in 2. Like the following examples:
nthIndexOf('the', 'the plain of the north is the coldest of them all', 2)
returns a value of 13
nthIndexOf('the', 'the plain of the north is the coldest of them all', 3)
returns a value of 26
As before, if no match is found, then a value of -1 is returned.
What happens with either the text you are searching for or the text you are searching in is blank?
If both parameters are blank, then a 0 is returned, because strangely enough a blank string can be found within a blank string.
If only the string you are searching for is blank, then it returns a -1 since the value was not found.
If only the string you are searching in is blank, then it depends.
- indexOf will return a 0
- lastIndexOf will return a value of “length of the string being searched for – 1”, which is weird, but that is the value it returns
- nthIndex will also return a 0
When you’re searching for a block of text within another block, it’s all pretty simple. Unless, of course, the block you search in is somehow blank. Then you can get some weird results. As long as you account for that scenario in your logic, then you shouldn’t have a problem. Happy hunting!
Husband, father, gamer, developer, manager, writer, creative, blogger, model railroader, Buckeyes fan