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
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:
We want to get just the value, so we can use indexOf
to work out the position of =
:
Now we have our index, we're able to take our substring:
This will pull everything from the position after the =
, to the end of the string, resulting in the following document:
Theme
Light