The “lastIndexOf” function is the corollary to the “indexOf” function, where it returns the last occurrence. It always returns a number, and it will return:
- Zero or greater for the position of the search text
- -1 is the text is not found.
Please note that the position starts at zero, not one. This is quite common for programmers but can be confusing for those who are not.
It follows a simple pattern.
- String to search
Let’s see some examples. First, let’s set up our test environment. Next, we’ll create an instant Flow with two parameters. This way, we can trigger the Flow with the parameters without changing it.
The formula will be as follows:
Let’s start with a simple example:
String 'Manuel T. Gomes' Search 'T.' will return 7
Notice that you can search for one or multiple characters. The search is case insensitive, meaning that “gOmeS” or “GoMES” are the same.
String 'Manuel T. Gomes' Search 'Teixeira' will return -1
The function can’t find the string, so that it will return -1.
Finally, let’s add multiple instances of the string and see what we get.
String 'Manuel T. Gomes where the T. is the last occurrence that I want to get' Search 'Teixeira' will return 26
I could not find a hard limitation for this function. I’ve passed strings with 30000 characters, and it returned almost instantly. But keep in mind that an undocumented limit may exist, so keep your strings as short as possible.
Here are some things to keep in mind.
Keep the parameters in variables.
Don’t pass them directly in the formula. You can do that, but it will make your formula quite prone to error. For example, if you want to check the string “Manuel’ T. Gomes'” (Notice the quotes), the function will return an error because it will consider the quotes as the end of the string. Having data on separate variables helps a lot in avoiding these issues.
There’s no real reason to do it, but if you find yourself in a situation where you have nested lastIndexOf functions in a formula, you should review it and make everything more straightforward.
Please note that formulas may have localization-based differences. For example, you should write “lastIndexOf” with “,“ separating each of the arguments, but if your regional settings are set to Portugal, you should use “;” instead.
Microsoft’s lastIndexOf Function Reference
Back to the Power Automate Function Reference.
Photo by David Clode on Unsplash