We’ve covered in the path the indexOf function, but today I wanted to cover the less known brother function, the “nthIndexOf” function. It does the same as the indexOf function; however, it doesn’t search for the first occurrence of the string inside another string but the one we provide. So let’s say that we have a word and want to find the second occurrence of that word. Then we would use the “nthIndexOf” with the index 2, and we would get:
- Zero or greater for the position of the search text
- -1 if the string cannot be 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.
Where to find it?
You can find the function in every action where a formula is supported. For example, let’s look at a “Compose” action:
As you can see, we can auto-complete by using the “tab” key. Let’s look at how to use it.
It follows a simple pattern.
- String to search
- Occurrence to find
Let’s start with a simple example:
If we provide the text:
'This is a test, and we'll try to find the second occurrence of the test word in the string' will return 67
Now let’s try to find a string that doesn’t exist in the text above:
It will return “-1” since we cannot fund it.
Notice that you can search for one or multiple characters. The search is case insensitive, meaning that “test” or “TesT” are the same.
Power Automate will return the same “67” value as before.
Depending on the size of your string, your expression may return an error, even if it’s correct. Please note that the expressions have a max size of 8,192 characters. If you have an expression that is even bigger than 1000, I would strongly advise that you break it into smaller, manageable formulas.
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 error-prone. 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 avoid these issues, making your actions much more reusable and easier to debug.
There’s no real reason to do it, but if you find yourself in a situation where you have nested not functions in a formula, you should review it and make everything more straightforward. I recommend constantly breaking things into smaller pieces so that you can understand what each step is doing.
Always add a comment
Adding a comment will also help avoid mistakes. Please indicate why you are trying to find the element and what it means. It may look obvious initially but will not be in a few months or years. It’s essential to enable faster debugging when something goes wrong.
Back to the Power Automate Function Reference.