Skip to content

indexOf - Finds the position of a given substring in a string

The indexOf function is useful for understanding where in a string a given substring appears.

The index is 0 based, meaning if a substring appears as the first letter of a given string, it is at position 0, not as position 1. If the index for a given substring can not be found, this function returns -1.

Syntax

indexOf(string: string, substring: string): number

Arguments

Name Type Required Description
string string true The parent string i.e the haystack
substring string true The substring whose index we seek i.e the needle

Example - Using indexOf as part of a substring

Before we can decide how much of a string we want to pull out, we first need to work out our index. indexOf is perfect for this. Consider this document:

{
    "msg": "result=Some value"
}

We want to get just the value, so we can use indexOf to work out the position of =:

create index_of_value from (msg.indexOf('=') + 1) # Convert to base 1

Now we have our index, we're able to take our substring:

create value from msg.substr(index_of_value + 1)

This will pull everything from the position after the =, to the end of the string, resulting in the following document:

{
    "msg": "result=Some value",
    "index_of_value": 7,
    "value": "Some value"
}